|
- Client端:
- HSocketClientMain.h
- #ifndef _H_SocketClientMain
- #define _H_SocketClientMain
- #include <WINSOCK2.H>
- #pragma comment(lib,"ws2_32.lib")
- #include <iostream>
- #include <string>
- using namespace std;
- #endif
- Main.cpp
- #include "HSocketClientMain.h"
- int main()
- {
- int err;
- WORD versionRequired;
- WSADATA wsaData;
- versionRequired=MAKEWORD(1,1);
- err=WSAStartup(versionRequired,&wsaData);//协议库的版本信息
- if (err)
- {
- printf("客户端的嵌套字打开失败!\n");
- return 1;//结束
- }
- else
- printf("客户端的已打开套接字\n");
- SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0);
- SOCKADDR_IN clientsock_in;
- clientsock_in.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
- clientsock_in.sin_family=AF_INET;
- clientsock_in.sin_port=htons(6000);
- if (0!=connect(clientSocket,(SOCKADDR*)&clientsock_in,sizeof(SOCKADDR)))//开始连接
- {
- printf("connection fail!\n");
- return 1;
- }
- char firstReceiveBuf[100];
- recv(clientSocket,firstReceiveBuf,101,0);
- printf("%s\n",firstReceiveBuf);
- while (1)
- {
- string input;
- cin>>input;
- send(clientSocket,input.c_str(),input.length()+1,0);
- char receiveBuf[100];
- recv(clientSocket,receiveBuf,101,0);
- printf("%s\n",receiveBuf);
- }
- closesocket(clientSocket);
- WSACleanup();
- return 0;
- }
- Server端:
- HSocketServerMain.h
- #ifndef _H_SocketServerMain
- #define _H_SocketServerMain
- #include <WINSOCK2.H>
- #pragma comment(lib,"ws2_32.lib")
- #include <iostream>
- #include <string>
- using namespace std;
- #endif
- Main.cpp
- #include "HSocketServerMain.h"
- int main()
- {
- //创建套接字
- WORD myVersionRequest;
- WSADATA wsaData;
- myVersionRequest=MAKEWORD(1,1);
- int err;
- err=WSAStartup(myVersionRequest,&wsaData);
- if (!err)
- {
- printf("已打开套接字\n");
- }
- else
- {
- //进一步绑定套接字
- printf("嵌套字未打开!");
- return 1;
- }
- SOCKET serSocket=socket(AF_INET,SOCK_STREAM,0);//创建了可识别套接字
- //需要绑定的参数
- SOCKADDR_IN addr;
- addr.sin_family=AF_INET; //地址簇
- addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//ip地址
- addr.sin_port=htons(6000);//绑定端口
- bind(serSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));//绑定完成
- listen(serSocket,5);//其中第二个参数代表能够接收的最多的连接数
- //////////////////////////////////////////////////////////////////////////
- //开始进行监听
- //////////////////////////////////////////////////////////////////////////
- SOCKADDR_IN clientsocket;
- int len=sizeof(SOCKADDR);
- SOCKET serConn=accept(serSocket,(SOCKADDR*)&clientsocket,&len);
- char firstConn[100];
- sprintf(firstConn,"welcome %s to here!",inet_ntoa(clientsocket.sin_addr));//找对对应的IP并且将这行字打印到那里
- send(serConn,firstConn,strlen(firstConn)+1,0);
- while (1)
- {
- char receiveBuf[100];//接收
- int i=recv(serConn,receiveBuf,strlen(receiveBuf)+1,0);
- if (i>0)
- {
- printf("%s\n",receiveBuf);
- char sendBuf[100];
- sprintf(sendBuf,"server get your message is %s",receiveBuf);//找对对应的IP并且将这行字打印到那里
- send(serConn,sendBuf,strlen(sendBuf)+1,0);
- }
- }
- closesocket(serConn);//关闭
- WSACleanup();
- return 0;
- }
复制代码 |
|