所以,我试图学习在python 3.2.5中正确使用套接字,我在互联网上找到了一个基本客户端和服务器的例子,并编辑了一下使用python 3.x(显示这里): 服务器:
print("Server")
from socket import *
myHost = ''
myPort = 2000
s = socket(AF_INET, SOCK_STREAM) # create a TCP socket
s.bind((myHost, myPort)) # bind it to the server port
s.listen(5) # allow 5 connections
while 1:
# wait for next client to connect
connection, address = s.accept() # connection is a new socket
while 1:
data = connection.recv(1024) # receive up to 1K bytes
if data:
connection.send('echo -> ' + data.decode("UTF-8"))
else:
break
connection.close() # close socket
客户端:
print("Client")
import sys
from socket import *
serverHost = 'localhost' # servername is localhost
serverPort = 2000 # use arbitrary port > 1024
s = socket(AF_INET, SOCK_STREAM) # create a TCP socket
s.connect((serverHost, serverPort)) # connect to server on the port
s.send(bytes("Hi", "UTF-8")) # send the data
while 1:
data = s.recv(1024) # receive up to 1KB
print(data)
但是,即使服务器没有运行,我的客户也会无限接收并打印"'''''''''''' (无限循环可能是不必要的,只是有一个例子。)我想知道为什么会这样。
我遇到的另一个问题是,一旦客户端启动并向其发送消息,服务器就会崩溃,它会发出以下消息:
Traceback (most recent call last):
File "C:\...\server.py", line 14, in <module>
connection.send('echo -> ' + data.decode("UTF-8"))
TypeError: 'str' does not support the buffer interface
答案 0 :(得分:1)
服务器失败的原因是;
connection.send('echo -> ' + data.decode("UTF-8"))
...尝试发送字符串,但send
想要一个字节数组。换句话说,你需要做类似的事情;
connection.send(bytes('echo -> ' + data.decode("UTF-8"), "UTF-8"))
在客户端,您没有考虑可以从服务器端关闭套接字,recv
将返回0字节。你的while循环最好不要打破一个空数组;
while 1:
data = s.recv(1024) # receive up to 1KB
if len(data) == 0: # but stop if socket is closed
break
print(data)