以前做过的很多东西都忘了,只能现在一点一点慢慢拾起来。
今天发一个基于python socket的聊天室程序。
因为很简单就不解释逻辑了。
上代码:
# server.py
# coding = utf-8
import socket
import threading
import time
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.bind(("127.0.0.1",23412))
sk.listen(10)
conn,address = sk.accept()
conn.sendall(bytes("连接成功!",encoding="utf-8"))
def recv_message():
res = ''
print('recv_message start ...')
while res != 'exit()':
res = str(conn.recv(1024),encoding="utf-8")
if (res != '')&(res != 'exit()'):
print(res)
def send_message():
inp = ''
print('send_message start ...')
while inp != 'exit()':
inp = input('please enter:')
conn.sendall(bytes(inp, encoding='utf-8'))
# conn.sendall(bytes('server test!',encoding='utf-8'))
try:
while True:
t1 = threading.Thread(recv_message())
t1.start()
t1.join()
t2 = threading.Thread(send_message())
t2.start()
except:
print("Error: unable to start thread")
# inp = ''
# while inp != 'exit()':
# inp = input('please enter:')
# conn.sendall(bytes(inp,encoding='utf-8'))
# inp = ''
# while inp != 'exit()':
# inp = input('please enter:')
# conn.sendall(bytes(inp),encoding='utf-8')
sk.close()
# client.py
# coding = utf-8
import socket
import threading
import time
obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
obj.connect(("127.0.0.1", 23412))
ret = str(obj.recv(1024), encoding="utf-8")
print(ret)
def recv_message():
res = ''
print('recv_message start ...')
while res != 'exit()':
res = str(obj.recv(1024), encoding="utf-8")
if res != '':
print(res)
def send_message(s):
# inp = ''
# while inp != 'exit()':
# inp = input('please enter:')
# obj.sendall(bytes(inp),encoding='utf-8')
obj.sendall(bytes(s, encoding='utf-8'))
try:
while True:
s = ''
while s!='exit()':
s = str(input('please enter::'))
t1 = threading.Thread(send_message(s))
t1.start()
t1.join()
t2 = threading.Thread(recv_message())
t2.start()
except:
print("Error: unable to start thread")
# inp = ''
# while inp != 'exit()':
# inp = input('please enter:')
# obj.sendall(bytes(inp),encoding='utf-8')
obj.close()