簡易的利用socket 實現tcp連線的程式,旨在簡化程式結構,給初學者乙個啟示的作用.
伺服器端程式:
//#include "stdafx.h"
#include #include #include using namespace std;
#pragma comment(lib,"ws2_32.lib") //新增ws2_32.lib
int _tmain(int argc, _tchar* argv)
cout << "initialize ws2_32.lib...done..." << endl;
//建立socket
socket srv_socket = socket(af_inet,sock_stream,0);
if (srv_socket == socket_error)
cout << "create socket...done..." << endl;
//填充sockaddr_in結構體用於bind
sockaddr_in srv_addr;
srv_addr.sin_addr.s_un.s_addr = htonl(inaddr_any);
srv_addr.sin_family = af_inet;
srv_addr.sin_port = htons(6500);
if (bind(srv_socket,(sockaddr*)&srv_addr,sizeof(srv_addr)) == socket_error)
cout << "bind...done..." << endl;
//使本地socket處於監聽狀態
int backlog = 3;
if (listen(srv_socket,backlog) == socket_error)
cout << "listen...done..." << endl;
//開啟接受狀態accept
//儲存傳送方的位址和埠資訊
socket from_socket;
sockaddr_in from_addr;
int fromlen = sizeof(sockaddr);
if ((from_socket = accept(srv_socket,(sockaddr*)&from_addr,&fromlen)) == socket_error)
cout << "accept...done..." << endl;
//接受傳送方的資料
char recvbuf[256];
if (recv(from_socket,recvbuf,256,0) == socket_error)
else
cout << recvbuf << endl;
cout << "recv...done..." << endl;
closesocket(srv_socket);
closesocket(from_socket);
wsacleanup();
return 0;}
客戶端程式:
//#include "stdafx.h"
#include #include #include using namespace std;
#pragma comment(lib,"ws2_32.lib") //新增ws2_32.lib
#define demon "demon"
#define wtype mb_ok | mb_iconerror
int _tmain(int argc, _tchar* argv)
cout << "initialize ws2_32.lib...done..." << endl;
//建立本地套接字
socket local_socket;
if ((local_socket = socket(af_inet,sock_stream,0)) == socket_error)
cout << "create socket...done..." << endl;
//填充sockaddr_in,用於connect
sockaddr_in cnt_addr;
cnt_addr.sin_addr.s_un.s_addr = inet_addr("127.0.0.1");
cnt_addr.sin_family = af_inet;
cnt_addr.sin_port = htons(6500);
if (connect(local_socket,(sockaddr*)&cnt_addr,sizeof(sockaddr)) == socket_error)
cout << "connect...done..." << endl;
//傳送資料
char buf[256] = "hello...";
if (send(local_socket,buf,strlen(buf)+1,0) == socket_error)
cout << "send...done..." << endl;
closesocket(local_socket);
wsacleanup();
return 0;
}
Socket程式設計 簡易測試socket UDP
簡易測試程式,用於測試使用socket 實現udp.程式結構簡單,僅有相關函式的使用.旨在明確新手對於socket的學習方向.伺服器程式 include stdafx.h include include include using namespace std pragma comment lib,w...
Socket 連線簡易程式設計
客戶端 include include using namespace std pragma comment lib,ws2 32.lib define port 4000 define ip address 127.0.0.1 int main int agrc,char agrv create ...
linux下簡易socket程式設計
最近研究了一下linux下的socket程式設計。這裡寫乙個簡易的版本上去。主要是分client和server兩個部分。對於client比較簡單,這裡僅做乙個簡單的client。可以給自己的server傳送一條訊息並且可以得到一條伺服器返回的訊息,之後結束程序。include include inc...