gpt4 book ai didi

python - 如何使用Python和socket发送和接收?

转载 作者:太空宇宙 更新时间:2023-11-03 20:02:11 24 4
gpt4 key购买 nike

我想发送到一个服务器,他有一个树莓派和一个在 Windows 上运行的客户端。问题是客户端可以连接,但之后,它仅在我关闭套接字时才发送消息。更进一步,可能原因是我使用了端口转发。

enter image description here

我的服务器代码

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the address given on the command line
server_address = ('', 1234)
sock.bind(server_address)
print >>sys.stderr, 'starting up on %s port %s' % sock.getsockname()
sock.listen(1)

while True:
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'client connected:', client_address
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
connection.sendall(data)
else:
break
finally:
connection.close()

和客户端

# coding: utf-8

import socket

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

socket.connect(("", 1234))

user_tab=input("What do you want to send?")
data=(str(user_tab))
print(data)
data = data.encode("utf-8")
socket.sendall(data)

print("send all")

d=socket.recv(128)
socket.close()
host, port =('', 1234)

socket.close()

最佳答案

抱歉,但我不明白你所说的问题。

客户端代码:

user_tab = input("What do you want to send?")
data = (str(user_tab))
print(data)
data = data.encode("utf-8")
socket.sendall(data)
print("send all")

user_tab = input("something else?")

d=socket.recv(1024)
socket.close()

ScreenShot

关于python - 如何使用Python和socket发送和接收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com