C TCP 伺服器客戶端Socket程式設計

2021-06-21 13:32:31 字數 2479 閱讀 9183

server.cpp

#include

#include

using namespace std;

#include

#define buf_size 64

#pragma comment(lib,"ws2_32.lib")

int main()

//建立監聽的socket

sserver=socket(af_inet,sock_stream,ipproto_tcp);

if(invalid_socket==sserver)

//設定伺服器socket位址

sockaddr_in addrserv;

addrserv.sin_family=af_inet;

addrserv.sin_port=htons(1298);

addrserv.sin_addr.s_un.s_addr=htonl(inaddr_any);

//繫結sockets server

retval=bind(sserver,(const struct sockaddr*)&addrserv,sizeof(sockaddr_in));

if(socket_error==retval)

//在sockets server上進行監聽

retval=listen(sserver,1);

if(socket_error==retval)

//接收來自客戶端的請求

printf("tcpserver start...\n");

sockaddr_in addrclient;

int addrclientlen=sizeof(addrclient);

sclient=accept(sserver,(sockaddr far*)&addrclient,&addrclientlen);

if(invalid_socket==sclient)

//迴圈接收客戶端的資料,直接客戶端傳送quit命令後退出

while(true)

//獲取當前系統時間

systemtime st;

getlocaltime(&st);

char sdatetime[30];

sprintf(sdatetime,"%4d-%2d-%2d-%2d:%2d:%2d:%2d",st.wyear,st.wmonth,st.wday,st.whour,st.wminute,st.wsecond);

//列印輸出的資訊

printf("%s,recv from client [%s:%d]:%s\n",sdatetime,inet_ntoa(addrclient.sin_addr),addrclient.sin_port,buf);

//如果客戶端傳送quit字串,則伺服器退出

if(strcmp(buf,"quit")==0)

//否則向客戶端傳送回顯字串

else

//釋放socket

closesocket(sserver);

closesocket(sclient);

wsacleanup();

//暫停,按任意鍵退出

system("pause");

return 0;}}

}client.cpp

#include

#include

#include

using namespace std;

#include

#define buf_size 64

#pragma comment(lib,"ws2_32.lib")

int main()

//建立監聽的socket

shost=socket(af_inet,sock_stream,ipproto_tcp);

if(invalid_socket==shost)

//設定伺服器socket位址

servaddr.sin_family=af_inet;

servaddr.sin_addr.s_un.s_addr=inet_addr("127.0.0.1");

//在實際應用中,建議將伺服器的ip位址和埠號儲存在配置檔案中

servaddr.sin_port=htons(1298);

//計算位址的長度

int sserveraddlen=sizeof(servaddr);

//鏈結伺服器

retval=connect(shost,(lpsockaddr)&servaddr,sizeof(servaddr));

if(socket_error==retval)

while(true)

//接收伺服器回傳的資料

retval=recv(shost,buf,sizeof(buf)+1,0);

printf("recv from server : %s\n",buf);

if(strcmp(buf,"quit")==0)

}return 0;

}

C tcp伺服器端

伺服器端 include stdafx.h include winsock2.h pragma comment lib,ws2 32.lib include using namespace std int tmain int argc,char ar 建立套接字 sserver socket af ...

C TCP客戶端 幫助類

初學c 因為專案需要寫的乙個理論上不會斷幀tcp幫助類 using system using system.collections.generic using system.linq using system.net.sockets using system.text using system.th...

伺服器與客戶端

建立socket操作,建立流式套接字,返回套接字型大小socksrv socket socket int af,int type,int protocol 第乙個引數,指定位址簇 tcp ip只能是af inet,也可寫成pf inet socket socksrv socket af inet,s...