下面这段程序中,服务器监听5000端口,客户端通过TCP连接上去以后,服务器会向客户端发送“Hello,success”字符串。程序非常简单,却实现了基本功能。
服务器端程序如下
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int listensock,connsock;
const char buff[]="Hello,success";
struct sockaddr_in serveraddr;
bzero(&serveraddr,sizeof(serveraddr));
listensock=socket(AF_INET,SOCK_STREAM,0);
serveraddr.sin_family=AF_INET;
serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);
serveraddr.sin_port=htons(5000);
bind(listensock,(struct sockaddr*)&serveraddr,sizeof(serveraddr));
printf("begin to listen on port 5000... ");
listen(listensock,1024);
connsock=accept(listensock,NULL,NULL);
send(connsock,buff,sizeof(buff),0);
close(connsock);
close(listensock);
}
客户端程序如下
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc,char *argv[])
{
int sockfd;
char buffer[100];
struct sockaddr_in serveraddr;
bzero(&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5000);
inet_pton(AF_INET,"192.168.9.9",&serveraddr.sin_addr);
sockfd=socket(AF_INET,SOCK_STREAM,0);
int value=connect(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
if(value==0)
printf("connect succeed ");
else printf("connect failed ");
recv(sockfd,buffer,sizeof(buffer),0);
printf("%s ",buffer); close(sockfd);
}