你要连接到哪个服务器?服务器需要在代码中有一个server_socket.accept()来接受连接。从只看你的客户很难判断。在
为了帮助你,我将附上一个我用python编写的多客户机聊天,也许你可以从中学习一些python,它有线程和多客户机套接字连接如果这对你来说太多了,我有一些更基本的东西,请给我一个评论
服务器:import socket
import select
import thread
import random
from datetime import date
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(5)
open_client_sockets = []
open_client_sockets_with_name = []
message_to_send = []
new_name = "new"
# recives a client socket and finds it in the list of open client sockets and returns its name
def find_name_by_socket(current_socket):
for client_and_name in open_client_sockets_with_name:
(client_address, client_name) = client_and_name
if client_address == current_socket:
return client_name
# this function takes a commend, executes it and send the result to the client
def execute(cmd):
if cmd == "DATE":
current_socket.send(str(date.today()))
elif cmd == "NAME":
current_socket.send("best server ever")
elif cmd == "RAND":
current_socket.send(str(random.randrange(1,11,1)))
elif cmd == "EXIT":
current_socket.send("closing")
open_client_sockets.remove(current_socket)
open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
current_socket.close()
else :
current_socket.send("there was an error in the commend sent")
def send_waiting_message(wlist):
# sends the message that needs to be sent
for message in message_to_send:
(client_socket, name, data) = message
if data[0] != '`':
print name + ": " + data
for client in wlist:
if client_socket != client:
client.send(name + ": " + data)
else: # this will execute a command and not print it
print "executing... " + data[1:]
execute(data[1:])
message_to_send.remove(message)
while True:
'''
rlist, sockets that you can read from
wlist, sockets that you can send to
xlist, sockets that send errors '''
rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets,open_client_sockets , [] )
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
new_name = new_socket.recv(1024)
print new_name + " connected"
open_client_sockets.append(new_socket)
open_client_sockets_with_name.append((new_socket, new_name))
else:
data = current_socket.recv(1024)
if data == "":
try:
open_client_sockets.remove(current_socket)
open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
except:
print "error"
print "connection with client closed"
else:
message_to_send.append((current_socket, str(find_name_by_socket(current_socket)) , str(data)))
send_waiting_message(wlist)
server_socket.close()
客户:
^{pr2}$