Python中的客户端服务器套接字编程

1 投票
1 回答
1184 浏览
提问于 2025-04-16 03:08

我在Python上写了一个客户端和服务器的套接字程序。在客户端和服务器中,我使用了回环地址(也就是本机地址)。但是请帮我一下,如何将这段代码应用到不同的客户端和服务器机器上?比如,服务器的IP是192.168.1.4,而客户端的IP是192.168.1.5。

# Server program

from socket import *

host = "localhost"
port = 21567
buf = 1024
addr = (host,port)

UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

while 1:
    data,addr = UDPSock.recvfrom(buf)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", data,"'"


UDPSock.close()


# Client program

from socket import *


host = "localhost"
port = 21567
buf = 1024
addr = (host,port)


UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg


while (1):
    data = raw_input('>> ')
    if not data:
        break
    else:
        if(UDPSock.sendto(data,addr)):
            print "Sending message '",data,"'....."

UDPSock.close()

1 个回答

3

在服务器代码中,不要用 'localhost',而是用 '192.168.1.5'(客户端的地址);在客户端代码中,用 '192.168.1.4'(服务器的地址)。

通常情况下,服务器不需要事先知道客户端的地址,但UDP比TCP(更常用的流式通信方式)要复杂很多;-)。

撰写回答