当前位置:  开发笔记 > 编程语言 > 正文

Python,如何通过TCP发送数据

如何解决《Python,如何通过TCP发送数据》经验,为你挑选了2个好方法。

我需要创建一个侦听TCP连接的简单服务器.如果它接收文本onoff然后它发送(回声)success.接收部分正在工作,但现在我需要它发回success.

码:

# import threading
import SocketServer

class TCPHandler(SocketServer.BaseRequestHandler): 

   def handle(self):
      self.msg = self.request.recv(1024).strip()
      if self.msg == "on":
         print "Turning On..."
         #ECHO "SUCCESS"        <----- I need the server to echo back "success"
      if self.msg == "off":
         print "Turning Off..."
         #ECHO "SUCCESS"        <----- 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()

小智.. 16

好吧,我之前做了一天非常好的教程,无法找到链接,但这里是代码

client.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))

对于服务器

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

它来自wiki ref:https://wiki.python.org/moin/TcpCommunication (2认同)


Arturo.. 14

python 3文档的更好方法是:

服务器

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

客户

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

希望能帮助到你.阿图罗



1> 小智..:

好吧,我之前做了一天非常好的教程,无法找到链接,但这里是代码

client.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))

对于服务器

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


它来自wiki ref:https://wiki.python.org/moin/TcpCommunication

2> Arturo..:

python 3文档的更好方法是:

服务器

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

客户

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

希望能帮助到你.阿图罗

推荐阅读
臭小子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有