'连接被拒绝'与套接字

时间:2018-02-26 10:57:26

标签: python sockets

客户端代码是用Python编写的。

客户端

import socket

host = '192.168.0.118'
#host = ''
port  = 5560

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))

while True:
    command = input("Enter your command")
    if command == 'EXIT':
        s.send(str.ecode(command))
        break
    elif command == 'KILL':
        s.send(str.encode(command))
        break
    s.send(str.encode(command))
    reply = s.recv(1024)
    print(reply.decode('utf-8'))
s.close()

服务器

import socket

host = ''
port = 5560
storedValue = "You man I done"
def setupServer():
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    print("yes Created")
    try:
        s.bind((host,port))
    except socket.error as msg:
        print(msg)
    print("socket bind complet")
    return s
def setupConnection():
    s.listen(1)
    conn,address = s.accept()
    print("done connection: " + address[0] + ":" + str(adress[1]))
    return conn

def GET():
    reply = storedValue
    return reply

def REPEAT (dataMessage):
    reply = dataMessage[1]
    return reply

def dataTransfer(conn):
    while True:
        data = conn.recv(1024)
        data = data.decode('utf-8')
        dataMessage = data.split(' ', 1)
        command = dataMessage[0]
        if command == 'GET':
            reply = GET()
        elif command == 'Repeat':
            reply = REPEAT(dataMessage)
        elif  command == 'EXIT':
             print("our client has left us")
             break            
        elif command == 'KILL':
            print("Shut down")
            s.close()
            break
        else:
           reply = 'Unknown Command'
           conn.sendall(str.encode(reply))
           print("Data has been sent")
    conn.close()#

s =  setupServer()

while True:
    try:
        conn = setupConnection()
        dataTransfer(conn)
    except:
        break

我得到了这个错误

Traceback (most recent call last):
  File "cookieClient.py", line 8, in <module>
    s.connect((host,port))
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

0 个答案:

没有答案