我尝试运行有关客户端和服务器的示例代码,但会出现一些错误:
服务器:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
客户:
import socket
HOST = '192.168.1.126' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
但是当客户端工作正常时,错误会显示在服务器上。
Connected by ('192.168.1.102', 11263)
Traceback (most recent call last):
File "C:\Users\Win7_Lab\Desktop\Server.py", line 15, in <module>
conn.sendall("data")
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
[Finished in 5.3s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\Server.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
错误出现的原因?在连接(&#39; 192.168.1.102&#39;,11263) 192.168.1.102是客户端IP但是什么是11263?
答案 0 :(得分:0)
您正在关闭while循环中的服务器连接尝试在侦听器完成后关闭连接:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
print data
if not data: break
conn.sendall(data)
# conn.close()
conn.close()
答案 1 :(得分:0)
端口11263
是一个所谓的ephemeral port,内核会自动选择它以便与您的服务器通信。