2016-11-06 141 views
1
#!/usr/bin/env python 
import socket 
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
clientsocket.connect(('192.168.1.123', 5162)) 
clientsocket.send('getval.1') 
clientsocket.close 
clientsocket.bind(('192.168.1.124', 5163)) 
clientsocket.listen(1) 
while True: 
    connection, address=clientsocket.accept() 
    value=connection.recv(1024) 
    print value 

我试图让python发送一条消息到服务器,并作为回应,服务器响应。然而,当我执行这个代码,它给了我Socket.error:[Errno 10022]提供的参数无效

Socket.error: [Errno 10022] An invalid argument was supplied 
+0

始终显示完整的错误消息(追溯)。有更多有用的信息。哪一行出问题? – furas

+0

首先你需要在'close()'中使用'()'来关闭它。第二:你不能再次使用封闭的套接字 - 你必须创建新的套接字。顺便说一句:如果你只改变服务器,你可以使用相同的连接来'send()'数据到服务器和'recv()'服务器的数据。 – furas

回答

0

看来你写的服务器和客户端 的混合代码下面的代码的一个简单的示例为Socket编程服务器端的第一和客户

第二

Server side code:

# server.py 
import socket           
import time 

# create a socket object 
serversocket = socket.socket(
      socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name 
host = socket.gethostname()       

port = 9999           

# bind to the port 
serversocket.bind((host, port))         

# queue up to 5 requests 
serversocket.listen(5)           

while True: 
    # establish a connection 
    clientsocket,addr = serversocket.accept()  

    print("Got a connection from %s" % str(addr)) 
    currentTime = time.ctime(time.time()) + "\r\n" 
    clientsocket.send(currentTime.encode('ascii')) 
    clientsocket.close() 

and now the client

# client.py 
import socket 

# create a socket object 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name 
host = socket.gethostname()       

port = 9999 

# connection to hostname on the port. 
s.connect((host, port))        

# Receive no more than 1024 bytes 
tm = s.recv(1024)          

s.close() 

print("The time got from the server is %s" % tm.decode('ascii')) 

服务器只是一直听任何客户端和WH它找到一个新的连接它返回当前日期时间并关闭客户端连接