1. 實現**
2. 聊天室服務端:tcp_server_chat.cpp
#include // winsock2的標頭檔案
#include
#pragma comment(lib, "ws2_32.lib")
using namespace std;
// stdcall的執行緒處理函式
dword winapi threadfun(lpvoid lpthreadparameter);
int main()
// 1. 建立流式套接字
socket s = socket(af_inet, sock_stream, ipproto_tcp);
if(s == invalid_socket)
// 2. 繫結埠和ip
sockaddr_in addr;
memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = af_inet;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int len = sizeof(sockaddr_in);
if(bind(s, (sockaddr*)&addr, len) == socket_error)
// 3. 監聽
listen(s,5);
// 主線程迴圈接收客戶端的連線
while(true) }
// 6.關閉監聽套接字
closesocket(s);
// 清理winsock2的環境
wsacleanup();
return 0;
}dword winapi threadfun(lpvoid lpthreadparameter)
; sprintf(buf,"歡迎 %d 進入聊天室!",c);
send(c,buf, 100, 0);
// 迴圈接收客戶端資料
int ret=0;
do ; ret = recv(c, buf2, 100, 0);
cout << c << " 說:" << buf2 << endl;
} while (ret!=socket_error && ret!=0);
cout << c << "離開了聊天室!";
return 0;
}啟動聊天室服務端:
3. 聊天室客戶端:tcp_client_chat.cpp
#include//winsock2的標頭檔案
#include
usievnyeyng namespace std;
//勿忘,鏈結dll的lib
#pragma comment(lib, "ws2_32.lib")
int main()
//1.建立流式套接字
socket s = socket(af_inet, sock_stream, ipproto_tcp);
if (s == invalid_socket)
//2.鏈結伺服器
sockaddr_in addr;
addr.sin_family = af_inet;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int len = sizeof(sockaddr_in);
if (connect(s, (sockaddr*)&addr, len) == socket_error)
//3接收服務端的訊息
char buf[100] = ;
recv(s, buf, 100, 0);
cout << buf << endl;
//3隨時給服務端發訊息
int ret = 0;
do ;
cout << "請輸入聊天內容:";
cin >> buf;
ret = send(s, buf, 100, 0);
www.cppcns.com } while (ret != socket_error&& ret != 0);
//4.關閉監聽套接字
closesocket(s);
//清理winsock2的環境
wsacleanup();
return 0;
}啟動2個客戶端
本文標題: c++基於socket多執行緒實現網路聊天室
本文位址:
基於TCP的Socket通訊 多執行緒
中引用的頭函式 include include include pragma comment lib,ws2 32.lib 伺服器端 1.初始化socket環境,建立套接字 wsadata wsadata word wversionrequested makeword 2,2 將兩個byte型合成乙...
基於多執行緒來實現併發的socket套接字
server import socket from threading import thread def server conn while true try data conn.recv 1024 except exception continue if data b q print 關閉子執行...
Socket 多執行緒
服務端 include include pragma comment lib,ws2 32 include void sendfuction socket sockconn void recvfunction socket sockclient void main if lobyte wsadata...