python 数据通信

服务器

from socket import *
import threading

IP = "localhost"
port = 40005

tcp_server = socket(AF_INET,SOCK_STREAM)
tcp_server.bind((IP, port))

tcp_server.listen(128)

print('listen at port :',port)


socks = []
st = []

def handle():
    while True:
        for client_socker in socks:
            try:
                from_client_msg = client_socker.recv(1024)
            except Exception as e:
                continue
            if from_client_msg == 'exit':
                break
            print('接受到数据 :',from_client_msg.decode("gbk"))
            st.append(from_client_msg.decode("gbk"))
            send_data = client_socker.send(str(st).encode("gbk"))

t = threading.Thread(target=handle)

if __name__ == '__main__':
    t.start()
    print()
    while True:
        client_socker, clientAddr = tcp_server.accept()
        print('connected by', clientAddr)
        client_socker.setblocking(0)
        socks.append(client_socker)


客户端

from socket import *
import sys

IP = "localhost"
port = 40005

tcp_socket = socket(AF_INET, SOCK_STREAM)

try:
	tcp_socket.connect((IP,port))
except Exception as e:
	print('服务器未启动')
	sys.exit()


while True:
	send_data = input("请输入发送内容:")
	tcp_socket.send(send_data.encode("gbk"))
	if send_data == 'exit':
		break
	try:
		from_server_msg = tcp_socket.recv(1024)
		data = from_server_msg.decode("gbk")
		print('recieved :',data)
	except:
		pass

tcp_socket.close()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值