有了 TCP/IP Server的编程知识及技巧http://blog.csdn.net/ieczw/article/details/19493311
对于Client (客户端的编程就简单了很多!)
图 1 服务器程序与客户端程序基本流程
图2 服务器与客户端通信图
还是按照以下几步来完成客户端与服务器间的通信:
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
WSADATA wsa_data;
int ret;
ret = WSAStartup(MAKEWORD(2.2),&wsa_data); // 返回非0失败
SOCKET fd_socket;
fd_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
如果创建失败返回INVALID_SOCKET
SOCKADDR_IN server_addr;
server_addr.sin_family = AF_INET; //Internet协议
server_addr.sin_port = htons(3400);
server_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
ret = connet(fd_socket,(SOCKADDR *)&server_addr,sizeof(SOCKADDR)); //连接失败则返回SOCKET_ERROR
如果想知道错误代码,则可以用 WSAGetLastError();
char send_buff[512];
memset(send_buff,0x0,512);
strcpy(send_buff,"Hello");
ret = send(fd_socket,buff,strlen(buff),0); //发送失败则返回SOCKET_ERROR
char buff[512];
memset(buff,0x0,512);
ret = recv(fd_socket,buff,512,0); //接收失败则返回 SOCKET_ERROR
ret为实际接收字节数;
closesocket(fd_socket);
WSACleanup();
请大家多多指教!