Linux下简单的socket通信实例
作者:网络转载 发布时间:[ 2015/6/16 11:31:27 ] 推荐标签:操作系统 socket
-执行:gcc client.c -o client 后启动 ./client 客户端程序 启动前先启动./server-----------------------------------------
server.c
1 #include <stdio.h>
2 #include <sys/socket.h>
3 #include <sys/types.h>
4 #include <string.h>
5 #include <netinet/in.h>
6 #include <stdlib.h>
7 #include <errno.h>
8 #include <unistd.h>
9 #include <arpa/inet.h>
10
11 #define MAXLINE 1024
12 int main(int argc,char **argv)
13 {
14 int listenfd,connfd;
15 struct sockaddr_in sockaddr;
16 char buff[MAXLINE];
17 int n;
18
19 memset(&sockaddr,0,sizeof(sockaddr));
20
21 sockaddr.sin_family = AF_INET;
22 sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
23 sockaddr.sin_port = htons(10004);
24
25 listenfd = socket(AF_INET,SOCK_STREAM,0);
26
27 bind(listenfd,(struct sockaddr *) &sockaddr,sizeof(sockaddr));
28
29 listen(listenfd,1024);
30
31
32 printf("Please wait for the client information ");
33
34 for(;;)
35 {
36 if((connfd = accept(listenfd,(struct sockaddr*)NULL,NULL))==-1)
37 {
38 printf("accpet socket error: %s errno :%d ",strerror(errno),err no);
39 continue;
40 }
41
42 n = recv(connfd,buff,MAXLINE,0);
43 buff[n] = '