我正在编码服务器-客户端程序,其中python为服务器,java为客户端。 当用户启动python服务器时,它将创建一个套接字并侦听客户端的连接(活动时,java客户端会每隔17秒尝试连接到服务器)。 这样做是为了向服务器用户显示活动客户端的列表。 听了20秒后,插座关闭了
服务器用户现在拥有所有活动客户端及其IP的列表。 服务器用户现在可以输入一条消息,该消息应该发送到活动的Java客户端之一。因此,他还需要输入应该接收该消息的一个客户端的IP(所有其他连接在传输任何数据之前都会关闭)。 为此,服务器在相同的地址上创建了一个新的套接字,但它只说:“ [Errno 98]地址已在使用中”,即使旧套接字已被s.close()关闭。仅当第一个套接字没有任何连接或我重新启动程序时,才能创建该套接字(对我来说似乎很奇怪...)。 我的整个python服务器:
import getpass
from requests import get
import os
import thread
import socket
import sys
import signal
import time
HOST = '0.0.0.0'
PORT = 1979
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created!'
try:
s.bind((HOST, PORT))
except socket.error as e:
print(e)
sys.exit()
print 'Socket bind complete'
s.settimeout(30)
s.listen(10)
print 'Listening...'
timeout = 10
timeout_start = time.time()
while time.time() < timeout_start + timeout:
try:
conn, addr = s.accept()
msg = conn.recv(1024)
print ('--------------------------------------')
print (msg)
except socket.timeout as e:
print(e,': Scan finished')
s.close()
break
print 'Client connected: ' + addr[0] + ':' + str(addr[1])
print ('--------------------------------------')
s.close()
print ('--------------------------------------')
print ('Please enter command')
while True:
x = raw_input("#").lower()
if x == "sercom":
serocom = raw_input('Enter the operation you want to do: ').lower()
if serocom == "rcos":
playername = raw_input('Enter command to be executed on the server: ')
opip = raw_input('Enter serverip (check above): ')
hosto = '0.0.0.0'
porto = 1979
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created!'
try:
soc.bind((hosto, porto))
except socket.error as e:
print(e)
sys.exit()
这时出现错误。 ([Errno 98]:地址已在使用中)
print 'Socket bind complete'
soc.settimeout(30)
soc.listen(10)
print 'Listening...'
timeout = 8
timeout_start = time.time()
while time.time() < timeout_start + timeout:
try:
conn, addr = soc.accept()
if addr[0] != opip:
conn.shutdown(socket.SHUT_RDWR)
conn.close()
else:
msg = conn.recv(1024)
print ('--------------------------------------')
print (msg)
conn.send((playername).encode('UTF-8'))
print ('Success! The following command has been sent to: ' + opip + ':' + playername )
print ('--------------------------------------')
soc.close()
break
except socket.timeout as e:
print(e,': Server not online or wrong ip')
soc.close()
break
else:
print("kk")