一、功能描述:
能够在Centos中创建TCP socket,实现Client给Server发送消息,Server能够Client发送消息。
二、代码如下:
①client代码:
#include <stdio.h>
#include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> int main() { int sockfd ; //socket标示 struct sockaddr_in serverAddr; //socket信息结构体serverAddr.sin_family = AF_INET; //domain
serverAddr.sin_port = htons(6666); //server port serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //server IPif((sockfd=socket(AF_INET,SOCK_STREAM,0))< 0){ //socket()
printf("socket ERR!\n"); return -1; } if( connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1){ //connect() printf("connect error: (errno: )\n"); return -1; } if(send(sockfd,"Sending string,logo_fox",strlen("Sending string,logo_fox"),0)<0){ //send() printf("send ERR!\n"); return -1; } close(sockfd);return -1;
}②server代码:
#include <stdio.h>
#include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <errno.h>int main(int argc ,char ** argv)
{ int sockfd, newfd; //sockfd: socket标示 ,newfd:accept标示 struct sockaddr_in serveraddr; //socket信息结构体 char buf[4096]; //数据缓存区 int n; //接收到的信息位数serveraddr.sin_family=AF_INET; //socket domain
serveraddr.sin_port = htons(6666); //socket port serveraddr.sin_addr.s_addr=htonl(INADDR_ANY); //socket IP info
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0){ //socket()
printf("Socket ERR!\n"); return -1; }if(bind(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr))<0){ //bind()
printf("Bind ERR!%s(errno:%d)\n",strerror(errno),errno); return -1; }if(listen(sockfd,4)<0){ //listen()
printf("Listen ERR!\n"); return -1; }while(1){
if((newfd=accept(sockfd,(struct sockaddr *)NULL,NULL))<0){ //accept() printf("accept ERR!\n"); return -1; }n = recv(newfd,buf,4096,0); //recv()
printf("n:%d\n",n); buf[n]='\n'; //将接收到的信息变为字符串 printf("recv msg from client is :%s\n",buf);close(newfd); //关闭accept
} close(sockfd); //关闭Socket }三、socket通讯流程