简体   繁体   English

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

[英]How to send and receive with Python and socket?

I want to send to a server that his a raspberry pi and a client that works on Windows.我想发送到他的树莓派和在 Windows 上运行的客户端的服务器。 The problem is that the client can connect, but after that, it only sends the message when I close the socket.问题是客户端可以连接,但之后,它只在我关闭套接字时发送消息。 Going further maybe the cause can be that I use portforwarding.更进一步,原因可能是我使用了端口转发。

enter image description here在此处输入图片说明

My server code我的服务器代码

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()

and the client和客户

# 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()

Sorry, but I don't see that problem what you talking about.对不起,但我看不出你在说什么。

Client code:客户端代码:

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截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM