我喜欢有一个端口首先用于连接到另一台服务器,之后该端口用作服务器而另一个客户端连接到它。
我现在使用python socket作为客户端我想将它用于服务器套接字。
我的代码:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print c
print 'Got connection from', addr
print s.recv(1024)
s.close
,输出
Traceback (most recent call last):
File "client.py", line 12, in <module>
s.listen(5) # Now wait for client connection.
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
我该怎么做? 谢谢你的答案!
答案 0 :(得分:0)
不确定你在这里想做什么。在我看来,您正在同一个应用程序中混合客户端和服务器代码。
作为参考,您可以创建一个简单的echo服务器,如下所示:
import socket
HOST = ''
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
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 = 'localhost'
PORT = 12349
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)