我有一個簡單的客戶端/服務器程序。如何在Python客戶端和C++服務器上使用套接字
客戶是用Python編寫的這一點:
import socket
import sys
HOST, PORT = "localhost", 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
for x in range(0, 10000):
print("Step 1")
s.send(b'Hello')
print("Step 2")
print(str(s.recv(1000)))
print(x)
我在Python寫的服務器是這樣的:
import socket
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
conn.sendall(data)
我要創建的服務器的C++版本。我這樣做:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
using namespace std;
#define SERVER_PORT htons(50007)
int main() {
char buffer[1000];
int n;
int serverSock=socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = SERVER_PORT;
serverAddr.sin_addr.s_addr = INADDR_ANY;
/* bind (this socket, local address, address length)
bind server socket (serverSock) to server address (serverAddr).
Necessary so that server can use a specific port */
bind(serverSock, (struct sockaddr*)&serverAddr, sizeof(struct sockaddr));
// wait for a client
/* listen (this socket, request queue length) */
listen(serverSock,1);
while (1 == 1) {
bzero(buffer, 1000);
sockaddr_in clientAddr;
socklen_t sin_size=sizeof(struct sockaddr_in);
int clientSock=accept(serverSock,(struct sockaddr*)&clientAddr, &sin_size);
//receive a message from a client
n = read(clientSock, buffer, 500);
cout << "Confirmation code " << n << endl;
cout << "Server received: " << buffer << endl;
strcpy(buffer, "test");
n = write(clientSock, buffer, strlen(buffer));
cout << "Confirmation code " << n << endl;
}
return 0;
}
它的工作原理一個時間,但它在客戶端的線str(s.recv(1000))
阻塞。
這是來自客戶機的輸出:
Step 1
Step 2
b'test'
0
Step 1
Step 2
這是來自服務器的輸出:
code 5
Server received: Hello
code 4
code 5
Server received: Hello
code 4
正如你所看到的,溝通是這樣的:
- 客戶端發送消息
- 服務器收到消息Ë
- 服務器發送消息
- 客戶端發送另一個消息
- 服務器收到一條消息,似乎發送另一個消息,但客戶沒有收到它。
我的錯誤是什麼?