我有一个简单的客户端/服务器程序。
客户端是用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
如您所见,沟通是这样的:
我的错误是什么?
答案 0 :(得分:3)
在C ++服务器中,您accept
连接,read
,write
,然后泄漏打开的套接字,然后等待下一个客户端连接。< / p>
将accept
移出循环,或在接受后添加内循环。
当你完成套接字时,close
套接字,在套接字编号的变量超出范围之前。
答案 1 :(得分:1)
有一点似乎很奇怪,在C版本中,你在循环内部接受了。
我认为这意味着在每次迭代时它都会尝试与新客户端建立新的套接字连接。