服务端
#tcp服务端
import socket
import threading
#创建连接
def data_recv(conn):
while True:
msg = conn.recv(1024)#接收客户端的信息
print("输出:" + msg.decode())
def msg_send(conn):
while True:
data = input("输入:")
conn.send(data.encode())#发送给客户端
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(('127.0.0.1',8888))#绑定ip和端口
sock.listen(5)#开始监听
print("正在监听....")
conn,addr = sock.accept()#连接成功后,返回一个新的套接字和客户端的地址
print(addr)
#数据收发
conn.send("你好".encode())
t1 = threading.Thread(target=data_recv,args=(conn,))
t2 = threading.Thread(target=msg_send,args=(conn,))
t1.start()
t2.start()
客户端
#客户端
import socket
import threading
#创建连接
def data_recv(conn):
while True:
msg = conn.recv(1024)#接收服务端的信息
print("输出:" + msg.decode())
def msg_send(conn):
while True:
data = input("输入:")
conn.send(data.encode())#发送给服务端
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect(('127.0.0.1',8888))
print("连接完成")
#数据收发
t1 = threading.Thread(target=data_recv,args=(sock,))
t2 = threading.Thread(target=msg_send,args=(sock,))
t1.start()
t2.start()
先运行服务端,再运行客户端