2017-12-09 4 views
0

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.

답변

0

서버에 HOST, PORT = "0.0.0.0", 9999로 변경해보십시오 :

는 오류입니다. 이제 서버는 루프백 인터페이스가 아닌 모든 인터페이스를 수신해야합니다. 빈 문자열 (예 : HOST, PORT = "", 9999)을 사용하여 동일한 결과를 얻을 수도 있습니다.

관련 문제