套接字未在localhost连接

时间:2016-01-07 19:44:50

标签: python python-2.7 sockets

我有两个文件。 .ng-enterserver.py。 客户代码:

client.py

服务器代码:

import socket
s = socket.socket()
try:
    s.connect(("localhost", 17894))
except socket.error:
    print "Couldn't connect."
    raise  # Useless, I know, but once I fix it I will change to exit()

data = ' '
BUFFER_SIZE = 1024

WELCOME_MSG = """Connecting to server.
The server should send you a list of commands when connected.
"""

print WELCOME_MSG
print s.recv(BUFFER_SIZE)  # Receive server's welcome message
while data:
    cmd = raw_input(">>> ")
    s.send(cmd)
    stuff = 1
    data = s.recv(BUFFER_SIZE)
    print data

    print "Server closed connection."
s.close()

我正在运行服务器,然后运行客户端。 一切都按预期,我收到欢迎消息并显示,当我尝试输入命令(或只是尝试向服务器发送任何东西)时问题就开始了

客户的错误:

import socket

s = socket.socket()
s.bind(("localhost", 17894))
s.listen(1)

BUFFER_SIZE = 1024

WELCOME_MSG = """...stuff..."""

while True:
    con, addr = s.accept()
    con.send(WELCOME_MSG)
    while True:
        data = s.recv(BUFFER_SIZE).split(" ")
        # some data processing, sets ans to a string
        con.send(str(ans))
    con.close()

服务器错误:

Traceback (most recent call last):
  File "...path.../Client.py", line 22, in <module>
    data = s.recv(BUFFER_SIZE)
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine

套接字编程对我来说很新鲜,所以我不知道发生了什么以及如何解决它。帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

我发现了我的错误。

import socket

s = socket.socket()
s.bind(("localhost", 17894))
s.listen(1)

BUFFER_SIZE = 1024

WELCOME_MSG = """...stuff..."""

while True:
    con, addr = s.accept()
    con.send(WELCOME_MSG)
    while True:
        data = s.recv(BUFFER_SIZE).split(" ") # HERE <----------------------------------
        # Some data processing, sets 'ans' to a string
        con.send(str(ans))
    con.close()

我正在使用绑定接收数据的套接字,而不是使用在con上打开的名为s.accept()的套接字。

答案 1 :(得分:0)

根据个人经验,尝试定义这样的接收函数:

def receive(sock):
    buf = sock.recv(BUFFER_SIZE)
    print (buf)

前一部分应该是这样的:

while True:
    con, addr = s.accept()
    con.sendall(WELCOME_MSG)
    while 1:
        receive(con)
        con.sendall(str(ans))
        #con.close()

<强>通知

如果您正在使用Python 3.x,则无法从缓冲区打印数据,因为在Python 3.x中,缓冲区输出类型是字节,您应该像这样对其进行解码:

data = data.decode("UTF-8")