伺服器端程式:
[cpp]view plain
copy
#include "winsock2.h"
#pragma comment(lib, "ws2_32.lib")
#include
using
namespace
std;
intmain(
intargc,
char
* argv)
//建立套接字
sserver = socket(af_inet, sock_stream, ipproto_tcp);
if(invalid_socket == sserver)
//伺服器套接字位址
addrserv.sin_family = af_inet;
addrserv.sin_port = htons(4999);
addrserv.sin_addr.s_addr = inaddr_any;
//繫結套接字
retval = bind(sserver, (lpsockaddr)&addrserv, sizeof
(sockaddr_in));
if(socket_error == retval)
//開始監聽
retval = listen(sserver, 1);
if(socket_error == retval)
//接受客戶端請求
sockaddr_in addrclient;
intaddrclientlen =
sizeof
(addrclient);
sclient = accept(sserver,(sockaddr far*)&addrclient, &addrclientlen);
if(invalid_socket == sclient)
while
(true
)
if(buf[0] ==
'0')
break
; cout << "客戶端傳送的資料: "
<< buf <
cout << "向客戶端傳送資料: "
; cin >> sendbuf;
send(sclient, sendbuf, strlen(sendbuf), 0);
} //退出
closesocket(sserver); //關閉套接字
closesocket(sclient); //關閉套接字
wsacleanup(); //釋放套接字資源;
return
0;
}
客戶端程式:
[cpp]view plain
copy
#include "winsock2.h"
#include
#pragma comment(lib, "ws2_32.lib")
using
namespace
std;
bool
recvline(socket s,
char
* buf);
//讀取一行資料
intmain(
intargc,
char
* argv)
//建立套接字
shost = socket(af_inet, sock_stream, ipproto_tcp);
if(invalid_socket == shost)
//設定伺服器位址
servaddr.sin_family =af_inet;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"
);
servaddr.sin_port = htons((short
)4999);
intnservaddlen =
sizeof
(servaddr);
//連線伺服器
retval=connect(shost,(lpsockaddr)&servaddr, sizeof
(servaddr));
if(socket_error == retval)
while
(true
)
//recvline(shost, bufrecv);
zeromemory(bufrecv, buf_size);
recv(shost, bufrecv,buf_size , 0); // 接收伺服器端的資料, 只接收5個字元
cout << endl <<"從伺服器接收資料:"
<< bufrecv;
cout<<"\n"
; }
//退出
closesocket(shost); //關閉套接字
wsacleanup(); //釋放套接字資源
return
0;
}
socket 實現客戶端與服務端通訊
python內的socket已經預設實現了tcp和udp兩種傳輸協議。本文通過乙個簡單的例子記錄一下socket的簡單使用方法。實現 客戶端和服務端通過tcp協議通訊,客戶端向服務端傳送訊息,服務端接收訊息後新增 too 字串後返回給客戶端,客戶端可以主動斷開連線。服務端 import socket...
服務端 客戶端Socket通訊
服務端 using system using system.collections.generic using system.net using system.net.sockets using system.text using system.text.regularexpressions usi...
socket 服務端於客戶端
usr bin env python coding utf 8 time 2017 8 23 15 33 author mr zhang site file 服務端.py software pycharm from socket import import subprocess,struct,jso...