程序调处来时候还是很高兴的。server向client发消息,client向server发消息。
//s.c
1 #include <sys/socket.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <stdio.h> 5 #include <linux/in.h> 6 #include <sys/types.h> 7 8 #define PORT 7891 9 10 int main() 11 { 12 int socketfd,accsocfd; 13 struct sockaddr_in s_addr,r_addr; 14 socklen_t len; 15 int recdata; 16 char buf[1024]; 17 memset(buf,0x00,sizeof(buf)); 18 //创建套接字 19 if(-1 == (socketfd = socket(AF_INET,SOCK_STREAM,0))){ 20 printf("socketfd is created failed! "); 21 return -1; 22 } ; 23 printf("socket create success! "); 24 25 //将本地协议地址与sockfd绑定 26 memset(&s_addr,0x00,sizeof(s_addr)); 27 s_addr.sin_family = PF_INET; 28 s_addr.sin_port = htons(PORT); 29 s_addr.sin_addr.s_addr = htons(INADDR_ANY);//inet_addr_any 一个服务器可能有多个网卡,随便从中选1个 30 if(-1 == bind(socketfd,(struct sockaddr*)&s_addr,sizeof(s_addr))){ 31 printf("bind failed! "); 32 return -1; 33 } 34 printf("bind suc! "); 35 36 //监听本地端口 37 if(-1 == listen(socketfd,10)){ 38 printf("listen failed! "); 39 return -1; 40 } 41 printf("listen suc! "); 42 43 while(1){ 44 len = sizeof(struct sockaddr); 45 accsocfd = accept(socketfd,(struct sockaddr *)&r_addr,&len); 46 if(-1 == accsocfd){ 47 printf("accept failed! "); 48 return -1; 49 } 50 printf("accept suc ! Server get connect from %x port is %x",ntohl(r_addr.sin_addr.s_addr),ntohl(r_addr.sin_port)); 51 52 53 //向客服端发送数据 54 if(-1 == write(accsocfd,"this is first data from sr! ",50)){ 55 printf("write failed! "); 56 return -1; 57 } 58 printf("write suc! "); 59 60 61 printf("********************* "); 62 63 char recvBuf[100]; 64 65 if(-1 ==recv(accsocfd, recvBuf, 100, 0)){ 66 printf("recv failed! "); 67 return -1; 68 } 69 printf("recv suc! "); 70 printf("recvBuf = [%s] ",recvBuf); 71 printf("recvBuf len is = [%d] ",strlen(recvBuf)); 72 73 close(accsocfd); 74 75 } 76 close(socketfd); 77 return 0; 78 }
//c.c
#include<sys/socket.h> #include<string.h> #include<linux/in.h> #include<sys/types.h> #include<stdio.h> #include<stdlib.h> /*流程: TCP:(面向连接、可靠) 服务器端 WSAStartup->socket->bind->listen->accept->recv/send->closesocket->WSACleanup 客户端:WSAStartup->socket->connect->recv/send->closesocket->WSACleanup */ #define PORT 7891 int main() { int csocfd; int recdata; char buf[1024]; memset(buf,0x00,sizeof(buf)); struct sockaddr_in mysockaddr; //创建套接字 if(-1 == (csocfd = socket(PF_INET,SOCK_STREAM,0))){ printf("csocfd failed! "); return -1; } printf("csocfd suc! "); //设置服务器的地址 memset(&mysockaddr,0x00,sizeof(mysockaddr)); mysockaddr.sin_family = PF_INET; mysockaddr.sin_port = htons(PORT); inet_pton(AF_INET,"172.19.230.113",&mysockaddr.sin_addr.s_addr); //s_add.sin_addr.s_addr= inet_addr("172.19.230.113"); /* ip转换为4字节整形,使用时需要根据服务端ip进行更改 */ //connect to the sr if(-1 == connect(csocfd,(struct sockaddr*)&mysockaddr,sizeof(mysockaddr))){ printf("connect failed! "); return -1; } printf("connect suc! "); if(-1 == (recdata = read(csocfd,buf,sizeof(buf)))){ printf("read failed! "); return -1; } printf("read suc! "); buf[recdata ] = '