服务器端:ser.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
int main()
{
struct sockaddr_in sad;
int sfd;
int cfd;
sfd=socket(AF_INET,SOCK_STREAM,0);
memset(&sad,0,sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_port=htons(8000);
inet_pton(AF_INET,"192.168.1.105", &(sad.sin_addr));
bind(sfd, (struct sockaddr*)&sad, sizeof(sad) );
listen(sfd,100);
while( cfd=accept(sfd, (struct sockaddr*)NULL, 0) )
{
char buf[256];
strcpy(buf,"server recv: ");
read(cfd, buf+13,236);
printf("%s\n",buf);
write(cfd, buf, 256);
close(cfd);
}
return 0;
}
客户端:client.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
int main()
{
struct sockaddr_in sad;
int sfd;
int cfd;
char name[256];
sfd= socket(AF_INET,SOCK_STREAM,0);
memset(&sad,0,sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_port=htons(8000);
inet_pton(AF_INET,"192.168.1.105", &(sad.sin_addr));
if(connect(sfd, (struct sockaddr*)&sad, sizeof(sad))<0)
{
printf("client connect error!\n");
exit(1);
}
snprintf(name, sizeof(name), "client send: %d ",getpid());
if(write(sfd, name, strlen(name))<0)
{
printf("client write error!\n");
exit(1);
}
if(read(sfd, name,256)<0)
{
printf("client read error!\n");
exit(1);
}
printf("client recv: %s\n", name);
return 0;
}
编译:
administrator@ubuntu:~/kkk$ gcc ser.c -o s
administrator@ubuntu:~/kkk$ gcc client1.c -o c
运行:
服务器:
administrator@ubuntu:~/kkk$ ./s &
[2] 5071
administrator@ubuntu:~/kkk$
客户端:(新开一个终端)
administrator@ubuntu:~/kkk$ ./c
client recv: server recv: client send: 5133
administrator@ubuntu:~/kkk$ ./c
client recv: server recv: client send: 5136
administrator@ubuntu:~/kkk$ ./c
client recv: server recv: client send: 5137
服务器的反应:
administrator@ubuntu:~/kkk$ ./c
server recv: client send: 5072
client recv: server recv: client send: 5072
administrator@ubuntu:~/kkk$ server recv: client send: 5133
server recv: client send: 5136
server recv: client send: 5137
PS:客户端发送“client send:pid”到服务器,服务器加上“server recv”头部以后打出来,发送回来,客户端再加上client recv后打印出来。