1、服务器端程序
功能:接收客户端发来的字符串,并把字符串原封不动地发送给客户端
#include <stdio.h>
#include <WinSock2.h>
#include "mystr.h"
#include "mysock.h"
#pragma comment(lib, "ws2_32")
int main() {
int iResult;
WORD wVersionRequested;
WSADATA wsaData;
SOCKET listenSocket;
SOCKET acceptSocket;
struct sockaddr_in service;
char received[256];
/*
initialize winsock...
create sock...
bind...
listen...
accept...
*/
/* read data and send it */
memset(received, 0, sizeof(received));
readString(acceptSocket, received, sizeof(received));
while (strLen(received) > 0 && strCmp(received, "quit") != 0) {
printf("received: %s\n", received);
writeString(acceptSocket, received);
memset(received, 0, sizeof(received));
readString(acceptSocket, received, sizeof(received));
}
printf("bye-bye!\n");
closesocket(listenSocket);
WSACleanup();
return 0;
}
2、客户端程序
功能:将输入的字符串发送给服务器端,并接收和打印服务器端发来字符串
#include <stdio.h>
#include <WinSock2.h>
#include "mystr.h"
#include "mysock.h"
#pragma comment(lib, "ws2_32")
int main() {
int iResult;
WORD wVersionRequested;
WSADATA wsaData;
SOCKET clientSocket;
struct sockaddr_in clientService;
char sent[256];
char received[256];
/*
initialize winsock...
create sock...
connect...
*/
/* write data and receive it */
memset(sent, 0, sizeof(sent));
printf("> ");
gets_s(sent, sizeof(sent) - 1);
while (strCmp(sent, "quit") != 0) {
writeString(clientSocket, sent);
memset(received, 0, sizeof(received));
readString(clientSocket, received, sizeof(received));
printf("received: %s\n", received);
printf("> ");
gets_s(sent, sizeof(sent) - 1);
}
printf("bye-bye");
closesocket(clientSocket);
WSACleanup();
return 0;
}
运行结果如下:
图1:客户端程序
图2:服务器端程序
注:
程序代码中引用的文件"mysock.h"请见有关socket数据传输的函数
程序代码中引用的文件"mystr.h"请见字符串处理函数的实现
程序代码中省略的代码请见初步认识windows socket服务器端与客户端编程
测试环境:Microsoft Visual Studio 2010