Python套接字编程 - ConnectionRefusedError:[WinError 10061]

时间:2018-04-03 11:27:45

标签: python sockets tcp

我正在尝试建立一个简单的TCP客户端 - 服务器连接,但有一个例外我无法解决。

这是我的服务器

   from socket import *
serverPort = 1200
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind('',serverPort)
print('Server has started: '+str(serverPort))
print('Server is ready to accept requests: ')
while 1:
    connectionSocket, addr = serverSocket.accept();
    print('Klienti u lidh me serverin %s me port $s' % addr)
    fjalia = connectionSocket.recv(1024)
    FjaliaMeShkronjaTeMedha = fjalia.upper()
    print(FjaliaMeShkronjaTeMedha)
    connectionSocket.send(FjaliaMeShkronjaTeMedha)
    connectionSocket.close()

这是我的客户:

import socket
serverName = 'localhost'
serverPort = 1200
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((serverName,serverPort)) #here is the error
var = input("jeni lidhur me serverin, shkruaje kerkesen")
s.sendall(str.encode(var))
data = s.recv(1024)
s.close()
print('te dhenat e pranuara nga serveri',repr(data))
然而,在这个特定部分的客户端,连接被拒绝

 s.connect((serverName,serverPort)) #here is the error

这是例外Error

有谁能告诉我为什么会这样?我是套接字的新手 提前致谢

1 个答案:

答案 0 :(得分:0)

代码问题

您的服务器不接受任何连接,这就是您看到此错误的原因。 您的服务器实现有一些问题让我高亮一点为您服务。 首先关闭serverSocket.bind('',serverPort)调用不正确你应该把它改成serverSocket.bind(('',serverPort))一个元组

其次,你的套接字必须处于监听模式才能监听绑定连接。

以下是固定代码:

对于服务器

from socket import *
serverPort = 1200
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(10)
print('Server has started: '+str(serverPort))
print('Server is ready to accept requests: ')
while 1:
     client_sock, address = serverSocket.accept()
     print('Klienti u lidh me serverin {0} me port $s'.format( address))
     fjalia = client_sock.recv(1024)
     FjaliaMeShkronjaTeMedha = fjalia.upper()
     print(FjaliaMeShkronjaTeMedha)
     client_sock.send(FjaliaMeShkronjaTeMedha)
     client_sock.close()

对于客户端

import socket
serverName = 'localhost'
serverPort = 1200
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((serverName,serverPort)) #here is the error
var = b"jeni lidhur me serverin, shkruaje kerkesen"
s.sendall((var))
data = s.recv(1024)
s.close()
print('te dhenat e pranuara nga serveri',repr(data))

从服务器端输出

Server has started: 1200
Server is ready to accept requests: 
Klienti u lidh me serverin ('127.0.0.1', 54722) me port $s
JENI LIDHUR ME SERVERIN, SHKRUAJE KERKESEN

客户端输出

te dhenat e pranuara nga serveri b'JENI LIDHUR ME SERVERIN, SHKRUAJE KERKESEN'

希望这会有所帮助