服務端**
/*服務端tcp程式一般流程
*1、建立socket
*2、繫結埠和ip
*3、監聽socket
*4、接收客戶端的請求
*5、從緩衝區中讀取資料
*/#include #include #include #include #include #include #include #include #define port 5000
#define ip "192.168.0.106"
#define backlog 5
int main()
;//讀寫緩衝區
struct sockaddr_in server_addr;
//需要獲取客戶端相關資訊
struct sockaddr_in client_addr;
socklen_t client_len;
client_len = sizeof(client_addr);
//建立socket
if ((listen_fd = socket(af_inet, sock_stream, 0)) < 0)
//繫結埠和ip
server_addr.sin_family = af_inet;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = inet_addr(ip);
if (bind(listen_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
//監聽socket
if (listen(listen_fd, backlog) < 0)
while(1)
//列印客戶端資訊
printf("connected with ip: %s: port:%d\n",
inet_ntop(af_inet, &client_addr.sin_addr, buf, 1024), ntohs(client_addr.sin_port));
while (1)
else }}
close(listen_fd);
return 0;
}
客戶端**
/*客戶端tcp程式一般流程
*1、建立socket
*2、向服務端發起連線
*3、向緩衝區中寫入資料
*/#include #include #include #include #include #include #include #include #define port 5000
#define ip "192.168.0.106"
int main()
;//讀寫緩衝區
struct sockaddr_in client_addr;
ssize_t size;
//建立socket
if ((client_fd = socket(af_inet, sock_stream, 0)) < 0)
//填充ip埠資訊
client_addr.sin_family = af_inet;
client_addr.sin_port = htons(port);
client_addr.sin_addr.s_addr = inet_addr(ip);
//向服務端發起連線
if (connect(client_fd, (struct sockaddr*)&client_addr, sizeof(client_addr)) < 0)
while(1)
if (strcmp(buf, "quit") == 0)
break;
if (write(client_fd, buf, strlen(buf)) != strlen(buf))
}close(client_fd);
return 0;
}
TCP伺服器 客戶端程式
server tcpserver.cpp檔案 include common initsock.h include cinitsock initsock 初始化winsock庫 int main 填充sockaddr in結構 sockaddr in sin sin.sin family af ine...
python網路程式設計(TCP客戶端 伺服器端實現)
下面的程式實現的功能 客戶端發來訊息,伺服器端加上時間戳返回給使用者 伺服器端 from socket import from time import ctime import os print os.getpid host post 21567 bufsiz 1024 addr host,post...
伺服器和客戶端 tcp通訊
在vs2013的環境下,伺服器 如下 include include stdafx.h include pragma comment lib,ws2 32.lib using namespace std define buffer rev 1024 define buffer send 1024 i...