我尝试使用Python 3.6制作聊天程序,但我认为我无法保持连接

时间:2018-05-07 12:41:32

标签: python-3.x

import socket

host = 'address' # as you know this isn't letters but I just write it as address for now.
port = 50000
bufsize = 1024

server = socket.socket()
server.bind((host, port))
server.listen(5) 

while 1:
 print("Waiting Connection")
 client, address = server.accept()
 print("Connected")
 welcomemsg = ("send messages")
 client.send(bytes(welcomemsg, "utf-8"))
 print("client info")
 print(address)
 msgfromclient = server.recv(bufsize).decode("utf8")
 client.send(bytes(msgfromclient, "utf-8"))
import socket

bufsize = 1024

client = socket.socket()

while 1:
 client.connect(('address', 50000))
 welcomemsg = client.recv(bufsize).decode("utf8")
 print(welcomemsg)
 msgtoserver = input()
 server.send(bytes(msgtoserver, "utf-8"))
 msgfromserver = client.recv(bufsize).decode("utf8")
 print(msgfromserver)

我想我可以连接服务器和客户端然后我可以让服务器向客户端发送欢迎消息,客户端可以接收该消息。

但在那之后,我认为我不能再保留服务器和客户端之间的连接。

我希望在服务器向客户端发送欢迎消息后,服务器和客户端保持连接,客户端向服务器发送消息,然后服务器再次将其发送给所有客户端(是的,我正在尝试制作聊天程序。)

我正在使用Windows。

0 个答案:

没有答案