使用 python 的简单套接字服务器和客户端程序

A simple socket server and client program using python

SocketServer程序
此代码在树莓派中:

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)

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 = "192.168.1.40", 3360
data='Hello'
#data = data.join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(data + "\n")

    # Receive data from the server and shut down
    received = sock.recv(1024)
finally:
    sock.close()
print "Sent:     {}".format(data)
print "Received: {}".format(received)

这里发送的数据应该是服务端接收,然后发回客户端。

这是错误:

[Errno 10061] No connection could be made because the target machine actively refused it.

尝试在服务器中更改为 HOST, PORT = "0.0.0.0", 9999。现在服务器应该监听 all 接口而不仅仅是环回接口。使用空字符串也可以实现相同的效果,即 HOST, PORT = "", 9999.