用python的socket库实现多人聊天室,但是只能在自己主机上打开多个客户端进行聊天,用别人的电脑输入我的电脑的IP地址却连不上我的服务端,这是为什么?
这是服务端
import socket
import threading
import socketserver
nick = ''
data = ''
def Notifyall(sentence):
global data
if condition.acquire():
data = sentence
condition.notifyAll()
condition.release()
def severs_send(conn, nick):
global data
while True:
if condition.acquire():
condition.wait()
if data:
try:
conn.send(data.encode('utf-8'))
condition.release()
except:
condition.release()
return
def severs_accept(conn, nick):
while True:
try:
indata = conn.recv(1024).decode('utf-8')
if not indata:
conn.close()
return
Notifyall(indata)
print(data)
except:
Notifyall(nick.decode() + 'error')
print(data)
return
condition = threading.Condition()
# ip = input("input the server ip address:")
port = 8888
sock = socket.socket()
print('socket created')
sock.bind((nick, port))
sock.listen(5)
print("socket new listening")
while True:
conn, address = sock.accept()
print('connect with' + address[0] + ':' + str(address[1]))
nick = conn.recv(1024)
Notifyall('WELCOME' + str(nick) + 'to this chatroom!')
print(data)
conn.send(data.encode(encoding='utf_8', errors='strict'))
threading.Thread(target=severs_accept, args=(conn, nick)).start()
threading.Thread(target=severs_send, args=(conn, nick)).start()
这是客户端
import socket
import threading
outstring=''
nick=''
instring=''
def client_send(sock):
global outstring
while True:
outstring=input()
outstring=nick+':'+outstring
sock.send(outstring.encode(encoding='utf_8', errors='strict'))
def client_accept(sock):
global instring
while True:
try:
instring=sock.recv(1024)
if not instring:
break
else:
print(instring)
except:
break
nick=input("input your nickname:")
ip=input("input the server ip address:")
port=8888
sock=socket.socket(socket.AF_INET)
sock.connect((ip,port))
sock.send(nick.encode(encoding='utf_8', errors='strict'))
threading.Thread(target=client_send,args=(sock,)).start()
threading.Thread(target=client_accept,args=(sock,)).start()