我只是一个小白,自己第一次动手写的基于win32控制台的socket通信程序,同时程序代码也只适合与初学者,写的不好的地方也多多包涵(同时希望大佬多多指教),我也希望我分享的成果供给有需要的小白,希望能帮助到你们。
成果展示:
客户端核心代码:
void chatClient() {
//请求协议版本
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
if (LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2) {
gotoXY(4, 8);
printf("请求协议版本失败");
}
else {
gotoXY(4, 8);
printf("请求协议版本成功");
}
//创建socket套接字
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
gotoXY(4, 9);
printf("套接字创建失败");
WSACleanup();
}
else
{
gotoXY(4, 9);
printf("套接字创建成功");
}
//创建协议族
SOCKADDR_IN addrConServer;
addrConServer.sin_family = AF_INET;
addrConServer.sin_addr.S_un.S_addr = inet_addr(IP_ADDR);
addrConServer.sin_port = htons(LISTEN_PORT);
//向服务器发出请求连接
int len = sizeof(SOCKADDR);
if (connect(clientSocket, (sockaddr*)&addrConServer, len) == SOCKET_ERROR) {
gotoXY(4, 10);
printf("连接失败:%d", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
}
else
{
gotoXY(4, 10);
printf("连接成功");
}
//数据通信以及线程
char ch[1024];
while (1) {
memset(ch, 0, 1024);
gotoXY(4, 11 + var_b);
//清楚遗留的文字
printf(" ");
gotoXY(4, 11 + var_b);
printf(">>");
scanf_s("%s", ch);
send(clientSocket, ch, strlen(ch), NULL);
var_b++;
if (var_b == 16) {
var_b = 0;
}
}
//
}
服务器端核心代码:
void chatServer() {
//请求协议版本
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
if (LOBYTE(wsaData.wVersion) != 2 ||
HIBYTE(wsaData.wVersion) != 2) {
gotoXY(10, 13);
printf("请求协议失败");
}
else {
gotoXY(10, 13);
printf("请求协议版本成功");
}
//创建Socket套件字
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET)
{
gotoXY(10, 14);
printf("socket套键字创建失败");
WSACleanup();
}
gotoXY(10, 14);
printf("socket套键字创建成功");
//协议族创建
SOCKADDR_IN addr = { 0 };
addr.sin_family = AF_INET;
addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addr.sin_port = htons(LISTEN_PORT);
//绑定
int len = sizeof(SOCKADDR);
int r = bind(serverSocket, (SOCKADDR*)&addr, len);
if (r == SOCKET_ERROR) {
gotoXY(10, 15);
printf("bind绑定失败");
closesocket(serverSocket);
}
gotoXY(10, 15);
printf("bind绑定成功");
//监听客户端请求
r = listen(serverSocket, 5);
if (r == SOCKET_ERROR) {
gotoXY(10, 16);
printf("监听失败");
closesocket(serverSocket);
}
gotoXY(10, 16);
printf("监听成功");
gotoXY(10, 17);
printf("连接中......");
//等待客户请求
while (1) {
//memset(buff, 0, 1024);
revSocket[count] = accept(serverSocket, (SOCKADDR*)&revAddr, &lengt);
if (revSocket[count] == INVALID_SOCKET) {
gotoXY(10, 17);
printf("客户端发出请求,服务器接收请求失败:");
closesocket(serverSocket);
WSACleanup();
}
else
{
gotoXY(10, 17);
printf("客户端发出请求,服务器接收请求成功");
gotoXY(22, 7);
printf("IP地址:%s", inet_ntoa(revAddr.sin_addr));
gotoXY(44, 7);
printf("对方端口:%d", ntohs(revAddr.sin_port));