简单Socket编程

01 server端:
02    
03 #include <WINSOCK2.H>
04 #include <stdio.h>
05 #pragma comment(lib,"ws2_32.lib")
06 void main()
07 {
08   //创建套接字
09   WORD myVersionRequest;
10   WSADATA wsaData;
11   myVersionRequest=MAKEWORD(1,1);
12   int err;
13   err=WSAStartup(myVersionRequest,&wsaData);
14   if (!err)
15   {
16    printf ( "已打开套接字/n" );
17   }
18   else
19   {
20    //进一步绑定套接字
21    printf ( "嵌套字未打开!" );
22    return ;
23   }
24   SOCKET serSocket=socket(AF_INET,SOCK_STREAM,0); //创建了可识别套接字
25   //需要绑定的参数
26   SOCKADDR_IN addr;
27   addr.sin_family=AF_INET;
28   addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY); //ip地址
29   addr.sin_port=htons(6000); //绑定端口
30    
31   bind(serSocket,(SOCKADDR*)&addr, sizeof (SOCKADDR)); //绑定完成
32   listen(serSocket,5); //其中第二个参数代表能够接收的最多的连接数
33    
34   //////////////////////////////////////////////////////////////////////////
35   //开始进行监听
36   //////////////////////////////////////////////////////////////////////////
37   SOCKADDR_IN clientsocket;
38   int len= sizeof (SOCKADDR);
39   while (1)
40   {
41    SOCKET serConn=accept(serSocket,(SOCKADDR*)&clientsocket,&len); //如果这里不是accept而是conection的话。。就会不断的监听
42    char sendBuf[100];
43     
44    sprintf (sendBuf, "welcome %s to bejing" ,inet_ntoa(clientsocket.sin_addr)); //找对对应的IP并且将这行字打印到那里
45    send(serConn,sendBuf, strlen (sendBuf)+1,0);
46    char receiveBuf[100]; //接收
47    recv(serConn,receiveBuf, strlen (receiveBuf)+1,0);
48    printf ( "%s/n" ,receiveBuf);
49    closesocket(serConn); //关闭
50   WSACleanup(); //释放资源的操作
51   }
52 }
53    
54    
55    
56 client端:
57    
58  
59 #include <WINSOCK2.H>
60 #include <stdio.h>
61 #pragma comment(lib,"ws2_32.lib")
62 void main()
63 {
64   int err;
65   WORD versionRequired;
66   WSADATA wsaData;
67   versionRequired=MAKEWORD(1,1);
68   err=WSAStartup(versionRequired,&wsaData); //协议库的版本信息
69   if (!err)
70   {
71    printf ( "客户端嵌套字已经打开!/n" );
72   }
73   else
74   {
75    printf ( "客户端的嵌套字打开失败!/n" );
76    return ; //结束
77   }
78   SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0);
79   SOCKADDR_IN clientsock_in;
80   clientsock_in.sin_addr.S_un.S_addr=inet_addr( "127.0.0.1" );
81   clientsock_in.sin_family=AF_INET;
82   clientsock_in.sin_port=htons(6000);
83   //bind(clientSocket,(SOCKADDR*)&clientsock_in,strlen(SOCKADDR));//注意第三个参数
84   //listen(clientSocket,5);
85   connect(clientSocket,(SOCKADDR*)&clientsock_in, sizeof (SOCKADDR)); //开始连接
86   char receiveBuf[100];
87   recv(clientSocket,receiveBuf,101,0);
88   printf ( "%s/n" ,receiveBuf);
89   send(clientSocket, "hello,this is client" , strlen ( "hello,this is client" )+1,0);
90   closesocket(clientSocket);
91   WSACleanup();
92 }

你可能感兴趣的:(编程,socket,Stream,server)