python - Is there a way to send two messages with socket
问题描述
Im trying to send a messages from the server to the client
I tried deleting the .close and puting a while loop on print but it still doesn't won't to work
Client
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
while True:
print (s.recv(1024))
Server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print ('Got connection from', addr)
x = str(input("ënter a message"))
data = x.encode()
c.send(data)
I expect the output to be 2 messages from the server but it is only sending 1 and then closing the connection
解决方案
切换你的accept
和while True:
线。接受连接后,继续在同一连接上发送。
请注意,TCP 是一种流式传输协议。没有“消息”的概念,只是一堆字节。如果您发送的速度足够快,例如:
c.send(b'abc')
c.send(b'def')
然后recv(1024)
可以收到b'abcdef'
。对于更复杂的通信,你必须定义一个协议和缓冲区recv
,直到你确定你有一个完整的消息。在这种情况下,一种简单的方法是读取直到找到换行符,或者在发送实际消息之前发送一个字节(或更多)来指示总消息的大小。
推荐阅读
- android - 在启动 Intent 之前检查 editText 的值
- tinymce - 如何更改 TinyMCE 图像插件中的属性文本?
- r - lapply 与分裂向量
- python - 在 matplotlib 注释文本中增加行分隔
- c# - 图像上的 WPF 链效果
- android - 无法在命令行中访问 C:\Program 文件
- java - 如果从 jar 运行,Java 类未找到异常,如果从 IntelliJ 运行则运行良好
- laravel - 停止在 Laravel 中渲染 Vue 组件
- python - 记住 Spyder 中具有不同 conda 环境的一组不同文件
- javafx - 使用数组的 JavaFX 折线图