[英]How to send and receive with Python and socket?
我想發送到他的樹莓派和在 Windows 上運行的客戶端的服務器。 問題是客戶端可以連接,但之后,它只在我關閉套接字時發送消息。 更進一步,原因可能是我使用了端口轉發。
我的服務器代碼
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.