简体   繁体   English

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

[英]A simple socket server and client program using python

SocketServer Program SocketServer程序
This code is in raspberry: 这段代码在树莓派中:

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

Socket Client Program 套接字客户端程序
This code is in my laptop: 此代码在我的笔记本电脑中:

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)

Here the data sent should be received to server and sent back to client. 在这里,发送的数据应被接收到服务器并发送回客户端。

This is the error: 这是错误:

[Errno 10061] No connection could be made because the target machine actively refused it. [Errno 10061]无法建立连接,因为目标计算机主动拒绝了该连接。

Try changing to HOST, PORT = "0.0.0.0", 9999 in the server. 尝试在服务器中更改为HOST, PORT = "0.0.0.0", 9999 Now the server should listen on all interfaces and not just the loopback interface. 现在,服务器应该侦听所有接口,而不仅是回送接口。 The same could also be achieved using an empty string ie HOST, PORT = "", 9999 . 使用空字符串(即HOST, PORT = "", 9999也可以实现相同的效果。

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

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