Python,如何通过 TCP 发送数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34653875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, How to Send data over TCP
提问by Ingmar05
I need to create a simple server that listens for TCP connections.
If it receives text on<EOF>
or off<EOF>
then it sends (echo) back success
. The receiving part is working, but now i need it to send back success
.
我需要创建一个简单的服务器来监听 TCP 连接。如果它收到文本,on<EOF>
或者off<EOF>
它发送(回显)回success
。接收部分正在工作,但现在我需要它发回success
。
Code:
代码:
# import threading
import SocketServer
class TCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.msg = self.request.recv(1024).strip()
if self.msg == "on<EOF>":
print "Turning On..."
#ECHO "SUCCESS<EOF>" <----- I need the server to echo back "success"
if self.msg == "off<EOF>":
print "Turning Off..."
#ECHO "SUCCESS<EOF>" <----- I need the server to echo back "success"
if __name__ == "__main__":
host, port = '192.168.1.100', 1100
# Create server, bind to local host and port
server = SocketServer.TCPServer((host,port),TCPHandler)
print "server is starting on ", host, port
# start server
server.serve_forever()
采纳答案by AbdulMueed
Well i did it a day before following a very good tutorial, cant find the link but here is the code
好吧,我在遵循一个非常好的教程前一天做了,找不到链接,但这是代码
client.py
客户端.py
import socket
host = socket.gethostname()
port = 12345 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
For server
服务器用
echo_server.py
echo_server.py
import socket
host = '' # Symbolic name meaning all available interfaces
port = 12345 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print host , port
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
try:
data = conn.recv(1024)
if not data: break
print "Client Says: "+data
conn.sendall("Server Says:hi")
except socket.error:
print "Error Occured."
break
conn.close()
回答by Arturo
A better approach from the python 3 docswould be:
来自 python 3文档的更好方法是:
Server
服务器
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Client
客户
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
print("Sent: {}".format(data))
print("Received: {}".format(received))
Hope it helps. Arturo
希望能帮助到你。阿图罗
回答by shashika11
If you need an endless/ continuous server connection you can use the following server code.
如果您需要无限/连续的服务器连接,您可以使用以下服务器代码。
Server Code
服务器代码
import socket # Import socket module
port = 50000 # Reserve a port for your service every new transfer wants a new port or you must wait.
s = socket.socket() # Create a socket object
host = "" # Get local machine name
s.bind(('localhost', port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print('Server listening....')
x = 0
while True:
conn, address = s.accept() # Establish connection with client.
while True:
try:
print('Got connection from', address)
data = conn.recv(1024)
print('Server received', data)
st = 'Thank you for connecting'
byt = st.encode()
conn.send(byt)
x += 1
except Exception as e:
print(e)
break
conn.close()
Client Code
客户代码
import socket # Import socket module
import os
import re
s = socket.socket() # Create a socket object
port = 50000 # Reserve a port for your service every new transfer wants a new port or you must wait.
s.connect(('localhost', port))
x = 0
st = str(x)
byt = st.encode()
s.send(byt)
# send message for hundred times
while x<100:
st = str(x)
byt = st.encode()
s.send(byt)
print(x)
while True:
data = s.recv(1024)
if data:
print(data)
x += 1
break
else:
print('no data received')
print('closing')
s.close()