#!/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] An invalid argument was supplied
答案 0 :(得分:4)
好像你写了服务器和客户端的混合代码 这里是一个简单的代码示例,用于套接字编程,第一个在服务器端,第二个在客户端
服务器端代码:
# 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()
现在是客户
# 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'))
服务器只是继续监听任何客户端,当它找到新连接时,它返回当前日期时间并关闭客户端连接