首页 > 解决方案 > 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

标签: python

解决方案


切换你的acceptwhile True:线。接受连接后,继续在同一连接上发送。

请注意,TCP 是一种流式传输协议。没有“消息”的概念,只是一堆字节。如果您发送的速度足够快,例如:

c.send(b'abc')
c.send(b'def')

然后recv(1024)可以收到b'abcdef'。对于更复杂的通信,你必须定义一个协议和缓冲区recv,直到你确定你有一个完整的消息。在这种情况下,一种简单的方法是读取直到找到换行符,或者在发送实际消息之前发送一个字节(或更多)来指示总消息的大小。


推荐阅读