python socket 初学 串行双向聊天室的简单实现

以前做过的很多东西都忘了,只能现在一点一点慢慢拾起来。

今天发一个基于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()

	



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值