服务器端代码
#include <stdio.h> #include <stdlib.h> #include <WinSock2.h> #include <cstring> #pragma comment(lib, "ws2_32.lib") //加载 ws2_32.dll int main() { WSADATA wsadata; WSAStartup( MAKEWORD(2, 2),&wsadata); SOCKET mysocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); SOCKADDR_IN myaddr; memset(&myaddr,0,sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_port = htons(1234); myaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); connect(mysocket,(SOCKADDR*)&myaddr,sizeof(SOCKADDR)); char buffer[1000]; //cin>>buffer; scanf("%s",buffer); send(mysocket,buffer,1000,0); closesocket(mysocket); //终止使用 DLL WSACleanup(); system("pause"); return 0; }
客户端代码
#include <iostream> #include <stdio.h> #include <winsock2.h> #pragma comment (lib, "ws2_32.lib") //加载 ws2_32.dll using namespace std; int main() { WSADATA wsadata; WSAStartup( MAKEWORD(2, 2),&wsadata); SOCKET mysocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); sockaddr_in myaddr; myaddr.sin_family = AF_INET; myaddr.sin_port = htons(1234); myaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); bind(mysocket,(SOCKADDR*)&myaddr,sizeof(SOCKADDR)); listen(mysocket,5); SOCKADDR getclient; int nsize = sizeof(SOCKADDR); SOCKET clientsocket = accept(mysocket,(SOCKADDR*)&getclient,&nsize); char buffer[1000]; int length = recv(clientsocket,buffer,1000,0); //send(clientsock,buffer,1000,0); printf("%s\n",buffer); closesocket(clientsocket); closesocket(mysocket); WSACleanup(); system("pause"); return 0; }