windows socket
//服务器
// winsvr.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <conio.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") void TCTServer() { SOCKET socksvr = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(INVALID_SOCKET == socksvr) { return; } struct sockaddr_in svraddr = {0}; svraddr.sin_family = AF_INET; svraddr.sin_port = htons(5678); svraddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); bind(socksvr, (struct sockaddr*)&svraddr, sizeof(svraddr)); listen(socksvr, SOMAXCONN); struct sockaddr_in clientaddr = {0}; int nLen = sizeof(clientaddr); SOCKET sockclient = accept(socksvr, (struct sockaddr*)&clientaddr, &nLen); char szText[100] = {0}; recv(sockclient, szText, 100, 0); printf("%s\n", szText); char szSend[100] = "Hello Client"; send(sockclient, szSend, sizeof(szSend), 0); getch(); closesocket(sockclient); closesocket(socksvr); } int main(int argc, char* argv[]) { WSADATA wsa = {0}; WSAStartup(MAKEWORD(2,2), &wsa); TCTServer(); return 0; }
//客户端
// wincli.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <conio.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") void TCPClient() { SOCKET sockclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(INVALID_SOCKET == sockclient) { return; } struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(5678); addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //连接到服务器 connect(sockclient, (struct sockaddr*)&addr, sizeof(addr)); char szSend[100] = "Hello Server"; send(sockclient, szSend, sizeof(szSend), 0); char szText[100] = {0}; recv(sockclient, szText, 100, 0); printf("%s\n", szText); getch(); closesocket(sockclient); } int main(int argc, char* argv[]) { WSADATA wsa = {0}; WSAStartup(MAKEWORD(2,2), &wsa); TCPClient(); return 0; }