windows下的socket编程(C++代码实现)
仅针对于⼩⽩在windows下的socket编程,(⼤佬请忽视),在⾃⼰的机器上亲测是成功的(WIN10环境 VS2013),先贴上⼀份演⽰效果:
⾸先得明⽩ 如何使⽤ socket 编程中常⽤的⽅法:
推荐博⽂:
建议看完上述博⽂后再来使⽤整篇代码:
Sever.cpp(服务端的代码)
#include<winsock2.h>
#include<iostream>
#include<string>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char* argv[]){
//初始化DLL
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsdata;
if (WSAStartup(sockVersion, &wsdata) != 0)
{
return1;
}
//创建套接字
socket编程聊天室基本流程
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET)
{
cout << "Socket error" << endl;
return1;
}
//绑定套接字
//绑定套接字
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(8888);
sockAddr.sin_addr.S_un.S_addr = INADDR_ANY;
if (bind(serverSocket, (sockaddr*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR){        cout << "Bind error" << endl;
return1;
}
//开始监听
if (listen(serverSocket, 10) == SOCKET_ERROR){
cout << "Listen error" << endl;
return1;
}
SOCKET clientSocket;
sockaddr_in client_sin;
char msg[100];//存储传送的消息
int flag = 0;//是否已经连接上
int len = sizeof(client_sin);
while (true){
if (!flag)
cout << "等待连接..." << endl;
clientSocket = accept(serverSocket, (sockaddr*)&client_sin, &len);
if (clientSocket == INVALID_SOCKET){
cout << "Accept error" << endl;
flag = 0;
return1;
}
if (!flag)
cout << "接收到⼀个链接:" << inet_ntoa(client_sin.sin_addr) << endl;
flag = 1;
int num = recv(clientSocket, msg, 100, 0);
if (num > 0)
{
msg[num] = '\0';
cout <<"Client say: "<< msg << endl;
}
string data;
getline(cin, data);
const char * sendData;
sendData = data.c_str();
send(clientSocket, sendData, strlen(sendData), 0);
closesocket(clientSocket);
}
closesocket(serverSocket);
WSACleanup();
return0;
}
Client.cpp(客户端的代码):
#include<winsock2.h>
#include<iostream>
#include<string>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD sockVersion = MAKEWORD(2, 2);
WSADATA data;
if (WSAStartup(sockVersion, &data) != 0)
{
return1;
}
while (true){
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET){
cout << "Socket error" << endl;
return1;
}
sockaddr_in sock_in;
sock_in.sin_family = AF_INET;
sock_in.sin_port = htons(8888);
sock_in.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (connect(clientSocket, (sockaddr*)&sock_in, sizeof(sock_in) )== SOCKET_ERROR){            cout << "Connect error" << endl;
return1;
}
string data;
getline(cin, data);
const char * msg;
msg = data.c_str();
send(clientSocket, msg, strlen(msg), 0);
char revdata[100];
int num = recv(clientSocket, revdata, 100, 0);
if (num > 0){
revdata[num] = '\0';
cout <<"Sever say:"<< revdata << endl;
}
closesocket(clientSocket);
}
WSACleanup();
return0;
}
⽣成两个exe⽂件后,先启⽤ 再启动。
代码暂且只实现了每次只能单条语句通话(⼀⼈⼀句的来),后续会继续完善的 。
待更新。。。。。。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。