pro*_*mer 6 python sockets socketserver
我用python编写了一个服务器程序.
我想要一个字符串,但我只有一个角色!我怎么才能收到一个字符串?
def handleclient(connection):
while True:
rec = connection.recv(200)
if rec == "help": #when I put help in the client program, rec = 'h' and not to "help"
connection.send("Help Menu!")
connection.send(rec)
connection.close()
def main():
while True:
connection, addr = sckobj.accept()
connection.send("Hello\n\r")
connection.send("Message: ")
IpClient = addr[0]
print 'Server was connected by :',IpClient
thread.start_new(handleclient, (connection,))
Run Code Online (Sandbox Code Playgroud)
使用TCP/IP连接,您的消息可能会碎片化.它可能一次发送一个字母,或者它可能会立即发送整个 - 你永远无法确定.
您的程序需要能够处理这种碎片.使用固定长度的数据包(因此您总是读取X字节)或在每个数据包的开头发送数据的长度.如果您只发送ASCII字母,您还可以使用特定字符(例如\n)标记传输结束.在这种情况下,您将阅读,直到消息包含\n.
recv(200) 不保证接收200个字节 - 200只是最大值.
这是服务器外观的一个示例:
rec = ""
while True:
rec += connection.recv(1024)
rec_end = rec.find('\n')
if rec_end != -1:
data = rec[:rec_end]
# Do whatever you want with data here
rec = rec[rec_end+1:]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3876 次 |
| 最近记录: |