gpt4 book ai didi

python : How to handle multiple clients and a server

转载 作者:行者123 更新时间:2023-12-01 06:13:14 25 4
gpt4 key购买 nike

我正在实现一个带有服务器和多个客户端的程序。所有客户端都将数据发送到服务器,服务器检查每个客户端的步骤。如果所有客户端的步骤都相同,则服务器会向所有客户端发送新数据以执行下一步。并且它一次又一次地继续这个过程。

但是,当我运行我的程序时,它无法相互通信。这是我的代码。你能给我一些提示吗?

客户端和服务器

#client
from socket import *
from sys import *
import time
import stat, os
import glob

# set the socket parameters
host = "localhost"
port = 21567
buf = 1024
data = ''
addr = (host, port)

UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.settimeout(100)

def_msg = "=== TEST ==="

#FILE = open("test.jpg", "w+")
FILE = open("data.txt","w+")

while (1):
#data, addr = UDPSock.recvfrom(buf)
print "Sending"
UDPSock.sendto(def_msg, addr)
#time.sleep(3)
data, addr = UDPSock.recvfrom(buf)

if data == 'done':
FILE.close()
break
FILE.write(data)

print "Receiving"
#time.sleep(3)

UDPSock.close()

# server program for nvt

from socket import *
import os, sys, time, glob
#import pygame
import stat

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

print 'test server'

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

msg = "send txt file to all clients"

#FILE = open("cam.jpg", "r+")
FILE = open("dna.dat","r+")
sending_data = FILE.read()
FILE.close()

tmp_data = sending_data

while (1):
#UDPSock.listen(1)
#UDPSock.sendto(msg, addr)
#FILE = open("gen1000.dat","r+")
#sending_data = FILE.read()
#FILE.close()


#print 'client is at', addr
data, addr = UDPSock.recvfrom(buf)
#time.sleep(3)
print data
#msg = 'hello'

#
tmp, sending_data = sending_data[:buf-6], sending_data[buf-6:]

if len(tmp) < 1:
msg = 'done'
UDPSock.sendto(msg, addr)
print "finished"
sending_data = tmp_data

UDPSock.sendto(tmp, addr)
print "sending"
#time.sleep(3)
UDPSock.close()

最佳答案

服务器必须执行socket()bind()listen()accept()序列code> (可能重复 accept() 来服务多个客户端),而客户端只需要序列 socket(), connect().

我首先看到的是你丢失的listen()。监听与套接字建立的连接。

更多信息请参见:link text

关于 python : How to handle multiple clients and a server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4650329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com