java客戶端
import java.io.*;
import java.net.*;
public class ClientDemo {
/**
* @param args
*/
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1",8888);
//獲取輸出流,用於客戶端向服務器端發送數據
// DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//獲取輸入流,用於接收服務器端發送來的數據
// DataInputStream dis = new DataInputStream(socket.getInputStream());
//客戶端向服務器端發送數據
// dos.writeUTF("ssssssssssss!");
//打印出從服務器端接收到的數據
// System.out.println(dis.readUTF());
//不需要繼續使用此連接時,記得關閉哦
// 重點是 這裡不懂DataInputStream 是什麼(功能不能實現):接收c發來的時間。!
InputStream ips = socket.getInputStream();
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String s = "";
while((s = br.readLine()) != null)
System.out.println(s);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
c服務器
#include "unp.h"
#include <time.h>
#include "stdio.h"
int main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
time_t ticks;
printf("綁定前");
listenfd = socket(AF_INET, SOCK_STREAM, 0);
printf("綁定前");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(8888); /* daytime server*/
printf("綁定前");
bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
printf("綁定結束%d",listenfd);
listen(listenfd,5);
printf("kaishi監聽");
for ( ; ; ) {
connfd = accept(listenfd, (SA *) NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24sguohaitao\r\n", ctime(&ticks));
printf("time=%.24s",buff);
write(connfd, buff, strlen(buff));
/*int n=0;
while((n=read(connfd,buff,256))>0){
printf("%s\n",buff);
if(fputs(buff,stdout)==EOF)
{
}*/
}
close(connfd);
return 0;
}