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

时间:2017-12-09 13:30:33

标签: python python-2.7 sockets client-server

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]无法建立连接,因为目标计算机主动拒绝它。

1 个答案:

答案 0 :(得分:0)

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