/cpp**
//服務端:
//cpp**
#include
#include
#include
using namespace std;
#pragma comment(lib, "ws2_32.lib") //載入函式庫windows socket
int main()
wsadata wsadata;
word sockversion = makeword(2, 2);
socket slisten = 0;
sockaddr_in sin = ;
sockaddr_in remoteaddr = ;
char sztext = "tcp server demo";
int naddrlen = 0;
naddrlen = sizeof(sockaddr_in);
//fill sin
sin.sin_port = htons(4567);
sin.sin_family = af_inet;
sin.sin_addr.s_un.s_addr = inaddr_any;
//init wsa
if (wsastartup(sockversion, &wsadata) != 0)
cout << "initlization failed!" << endl;
exit(0);
slisten = socket(af_inet, sock_stream, ipproto_tcp);
if (bind(slisten, (lpsockaddr)&sin, sizeof(sin)) == socket_error)
cout << "bind failed!" << endl;
return 0;
if (listen(slisten, 2) == socket_error)
cout << "listen failed!" << endl;
return 0;
socket sclient = inaddr_any;
while (true)
sclient = accept(slisten, (sockaddr*)&remoteaddr, &naddrlen);
if (sclient == invalid_socket)
cout << "accept failed!" << endl;
continue;
send(sclient, sztext, strlen(sztext), 0);
closesocket(sclient);
closesocket(slisten);
wsacleanup();
//以上為服務端**,以下為客戶端**,分開編譯
//服務端:
#include
#include
#include
using namespace std;
#pragma comment(lib, "ws2_32.lib")
int main()
wsadata wsadata;
word sockversion = makeword(2, 2);
socket sock = 0;
if (wsastartup(sockversion, &wsadata) != 0)
cout << "initlization failed!" << endl;
exit(0);
sock = ::socket(af_inet, sock_stream, ipproto_tcp);
if (sock == invalid_socket)
cout << "failed socket!" << endl;
return 0;
sockaddr_in sin;
sin.sin_family = af_inet;
sin.sin_port = htons(4567);
sin.sin_addr.s_un.s_addr = inet_addr("127.0.0.1");//本機同時執行客戶端與服務端程序,獲取本機內部ip
if (connect(sock, (sockaddr*)&sin, sizeof(sockaddr)) == -1)
cout << "connect failed!" << endl;
return 0;
char buffer[256] = "/0";
int nrecv = 0;
nrecv = recv(sock, buffer, 256, 0);
if (nrecv > 0)
buffer[nrecv] = '/0';
cout << "reveive data: " << buffer << endl;
closesocket(sock);
wsacleanup();
TCP客戶端服務端demo
服務端程式 include include include include include include include int main 列印握手成功的客戶端 struct sockaddr in servaddr socklen t nservlen sizeof servaddr getso...
socket 服務端 客戶端(注釋版)
usr bin env python coding utf 8 time 2017 8 22 16 14 author mr zhang site file server.py software pycharm from socket import import subprocess import ...
TCP通訊,多客戶端通訊(客戶端 服務端)
客戶端和伺服器間的交流,客戶端傳送資訊,伺服器接收到,並返回資訊 長連線建立socket連線服務端 指定ip位址,埠號 通過ip位址找對應的伺服器 呼叫socket的getinputstream 和getoutputstream 方法獲取和服務端相連的io流 輸入流可以讀取服務端輸出流寫出的資料 輸...