简体   繁体   English

C 服务器套接字拒绝连接 python 客户端

[英]C server socket refusing the connection of a python client

I am trying to make a messenger program (that currently has a ton of bugs so please dismiss them) and for some reason, the server wont let the clients connect.我正在尝试制作一个信使程序(目前有很多错误,所以请忽略它们),出于某种原因,服务器不会让客户端连接。 I have tried changing the port, but nothing works.我尝试更改端口,但没有任何效果。 I get the following error (for my client, which is in python) (this is on a mac, but I have tried the client on a windows computer, still nothing):我收到以下错误(对于我的客户端,它在 python 中)(这是在 mac 上,但我已经在 windows 计算机上尝试了客户端,仍然没有):

Traceback (most recent call last):
  File "msgclient.py", line 31, in <module>
    Program()
  File "msgclient.py", line 8, in __init__
    self.s.connect((IP, PORT))
ConnectionRefusedError: [Errno 61] Connection refused

Here is the code for the server (written in c):这是服务器的代码(用c编写):

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>

#define MAXCLIENTS 256
#define MAXMSG 269
#define PORT 9989

void forward(int clientslist[MAXCLIENTS], char* msg) {
    int x;
    for (x=0; x < MAXCLIENTS;  x++){
        send(clientslist[x], msg, sizeof(msg), 0);
    }
    return;
}

int main(){
    int s = socket(AF_INET, SOCK_STREAM, 0);
    int clients[MAXCLIENTS];
    int clientcounter = 0;

    fd_set socketlist, readlist;
    FD_ZERO(&socketlist);
    FD_SET(s, &socketlist);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = INADDR_ANY;

    bind(s, (struct sockaddr*) &server, sizeof(server));
    listen(s, MAXCLIENTS);
    int clientsocket;
    int i;
    int rc;
    int max = s;
    void* msg = (char *) malloc(MAXMSG+1);
    void* usr = (char *) malloc(14);

    while (1){
        readlist = socketlist;
        select(FD_SETSIZE, &readlist, NULL, NULL, NULL);
        for (i=0; i<max+1; i++){
            if(FD_ISSET(i, &readlist)){
                if (i == s){
                    clientsocket = accept(s, NULL, NULL);
                    FD_SET(clientsocket, &socketlist);
                    clients[clientcounter] = clientsocket;
                    clientcounter++;
                    rc = recv(clientsocket, usr, 10, 0);
                    printf("Connection received from %s\n", usr);
                    usr = "\0";
                    if (clientsocket > max+1){
                        max = clientsocket;
                    }
                } else {
                    rc = recv(i, msg, MAXMSG, 0);
                    if (rc > 0){
                        forward(clients, msg);
                    } else{
                        close(i);
                    msg = "\0";
                    }
                }
            }

        }
    }
    return 0;
}

and the client (written in python):和客户端(用python编写):

import socket

class Program:
    def __init__(self):
        IP = socket.gethostbyname(socket.gethostname())
        PORT = 9989
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((IP, PORT))
        self.user = self.username()
        self.s.send(bytes(self.user, "utf-8"))
        while True:
            received = self.s.recv(269)
            received = received.decode("utf-8")
            print(received)
            self.enter()


    def username(self):
        name = str(input("Enter a username (10 character max): "))
        if len(name) > 10:
            print("Username is larger than 10; try again")
            self.username()
        return name;

    def enter(self):
        msg = str(input("Enter a message>> "))
        if msg != "":
            self.s.send(bytes(f"{self.user}>> {msg}", "utf-8"))

if __name__ == "__main__":
    Program()

regarding the function:关于 function:

void forward(int clientslist[MAXCLIENTS], char* msg)

and

send(clientslist[x], msg, sizeof(msg), 0);

The expression: sizeof(msg) will return a value (depending on your underlying hardware and certain compiler parameters) of 4 or 8, Not what you want.表达式: sizeof(msg)将返回 4 或 8 的值(取决于您的底层硬件和某些编译器参数),这不是您想要的。 Suggest passing the actual number of bytes to transmit.建议传递实际要传输的字节数。

regarding the function:关于 function:

void forward(int clientslist[MAXCLIENTS], char* msg)

and the statement:和声明:

return; 

The return; return; statement is completely unnecessary.声明是完全没有必要的。 Suggest removing that statement.建议删除该声明。

regarding:关于:

int s = socket(AF_INET, SOCK_STREAM, 0); 

This statement can fail.此语句可能会失败。 Always check (if socket < 0) then handle the error始终检查(如果套接字 < 0)然后处理错误

regarding:关于:

server.sin_addr.s_addr = INADDR_ANY;

INADDR_ANY has the value: "0.0.0.0" which cannot be directly assigned. INADDR_ANY的值为:“0.0.0.0”,不能直接赋值。 Suggest:建议:

server.sin_addr.s_addr = htonl(INADDR_ANY);

OT: regarding: OT:关于:

bind(s, (struct sockaddr*) &server, sizeof(server));

and

listen(s, MAXCLIENTS); 

These functions can fail.这些功能可能会失败。 Always check the returned value to assure the operation was successful.始终检查返回值以确保操作成功。

OT: regarding: OT:关于:

void* msg = (char *) malloc(MAXMSG+1);

and similar statements.和类似的说法。 In C, the returned type is void* which can be assigned to any pointer.在 C 中,返回的类型是void* ,可以分配给任何指针。 Casting just clutters the code and is error prone.强制转换只会使代码混乱并且容易出错。 even this statement has an error in the cast.即使这个陈述在演员表中也有错误。 Suggest removing that cast.建议删除该演员表。

regarding:关于:

readlist = socketlist; 
select(FD_SETSIZE, &readlist, NULL, NULL, NULL); 
for (i=0; i<max+1; i++) 
{ 
    if(FD_ISSET(i, &readlist))
    { 
        if (i == s)
        { 

This code sequence forces serial handling of the incoming sockets.此代码序列强制对传入的 sockets 进行串行处理。 Much better to generate a 'thread pool', then use accept() and pass the resulting client socket to an idle thread.生成一个“线程池”要好得多,然后使用 accept() 并将生成的客户端套接字传递给空闲线程。 The thread then performs all the communication with the client, then, when finishing with the client, closes the client socket.然后线程执行与客户端的所有通信,然后在与客户端完成时关闭客户端套接字。

regarding:关于:

select(FD_SETSIZE, &readlist, NULL, NULL, NULL);

There must already be an open socket to the client, which there is none, so no communication occurs.客户端必须已经有一个打开的套接字,但没有,因此不会发生通信。

there may be other problems, but this should aim you in the right direction.可能还有其他问题,但这应该使您朝着正确的方向前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM