这是最简单了的Socket通讯了,因为只有客户端可以向服务端程序发送消息,不能接受消息。而服务端只能够接受消息,不能够发送消息。
#######################
server
#######################
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int admin_socket,data_socket;
struct sockaddr_in name;
char buf[1024];
int nbyte,i;
admin_socket=socket(AF_INET,SOCK_STREAM,0);
if(admin_socket<0)
printf("*********Error******");
name.sin_family=AF_INET;
name.sin_addr.s_addr=INADDR_ANY;
name.sin_port=htons(12345);
if(bind(admin_socket,(struct sockaddr*)&name,sizeof(name))<0)
printf("*******Blind error********");
if(listen(admin_socket,5)<0)
printf("******Listen error********");
if((data_socket=accept(admin_socket,0,0))<0)
printf("******Connet refused*********");
else
printf("Connet data_socket=%d",data_socket);
for(;;)
{
nbyte=read(data_socket,buf,1086);
if(nbyte==0)
{
printf("*********Falied********/n");
close(data_socket);
exit(0);
}
for(i=0;i<nbyte;i++)
printf("%c",buf[i]);
printf("\n");
}
}
#######################
client.c
######################
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
int main (int argc ,char **argv)
{
int sock;
struct sockaddr_in name;
char sbuf[1086];
if(argc<2)
{
printf("<<<<<<<<22222222");
exit(0);
}
sock=socket(AF_INET,SOCK_STREAM,0);
if(sock<0)
printf("*****Error******");
name.sin_family=AF_INET;
name.sin_addr.s_addr=htonl(inet_network(argv[1]));
name.sin_port=htons(12345);
if(connect(sock,(struct sockaddr*)&name,sizeof(name))==-1)
{
printf("*******Connect failed*******");
exit(1);
}
printf("******Connected********");
for(;;)
{
if(fgets(sbuf,1086,stdin)==NULL) break;
if(write(sock,sbuf,strlen(sbuf))<0)
{
printf("sending message error!\n");
close(sock);
printf("connection closed!\n");
exit(0);
}
}
return 1;
}
分别用两个终端编译执行客户端和服务端。在客户端输入Ip本地为:127.0.0.1之后,就可以通讯了。稍复杂的请见:http://blog.youkuaiyun.com/yilip/article/details/7705462