一、Socket是什么
Socket本身不是一个协议,是一个套接字,操作系统为了方便大家直接使用tcp协议而存在的一个抽象层,它把复杂的TCP/IP协议隐藏在接口后面。
二、Socket编程
三、socket编程实例
socket通信实例一:
程序结构:
socket_server.py
#socket服务端 import socket server_socket = socket.socket() #绑定到0.0.0.0 8000端口 server_socket.bind(('0.0.0.0',8000)) server_socket.listen() #阻塞等待连接 socket,add=server_socket.accept() print(socket) print(add) data=bytes('','utf-8') while True: tmp_data=socket.recv(1024) print(tmp_data) if tmp_data: data+=tmp_data else: break; print(data) socket.close()
socket_client.py
#socket客户端 import socket client = socket.socket() client.connect(('localhost', 8000)) #client.send(b'Hello World') client.send('Hello World'.encode('utf-8')) client.close()
分别设置server、client程序并行执行
更改选项,设置并行执行
先执行server,后执行client,执行结果如下,可以看到client已经将数据传到server上了
socket通信实例二:(改了客户端输出)
socket_server.py
#socket服务端 import socket server_socket = socket.socket() #绑定到0.0.0.0 8000端口 server_socket.bind(('0.0.0.0',8000)) server_socket.listen() #阻塞等待连接 socket,add=server_socket.accept() print(socket) print(add) data=bytes('','utf-8') while True: tmp_data=socket.recv(1024) print(tmp_data) if tmp_data: data+=tmp_data if tmp_data.decode("utf-8").endswith("#"): break else: break; print(data) socket.close()
socket_client.py #号键输出程序结束
#socket客户端 import socket client = socket.socket() client.connect(('localhost', 8000)) #当输出完成后,以#号结尾,即为完成 while True: data = input() client.send(data.encode('utf-8')) client.close()
程序运行结果:
socket通信实例三:
socket_server.py
#socket服务端 import socket import threading server_socket = socket.socket() #绑定到0.0.0.0 8000端口 server_socket.bind(('0.0.0.0',8000)) server_socket.listen() #获取客户端连接并启动线程去处理 def handle_client(server_socket,addr): while True: tmp_data = socket.recv(1024) print(tmp_data.decode("utf-8")) input_data=input() socket.send(input_data.encode("utf-8")) while True: # 阻塞等待连接 socket, add = server_socket.accept() #启动一个线程去处理新的用户连接 client_thread=threading.Thread(target=handle_client,args=(socket,add)) client_thread.start()
socket_client.py
#socket客户端 import socket client = socket.socket() client.connect(('localhost', 8000)) #当输出完成后,以#号结尾,即为完成 while True: data = input() client.send(data.encode('utf-8')) server_data = client.recv(1024) if server_data: if server_data.decode("utf-8").endswith("#"): break else: break; print("server response:{}".format(server_data.decode("utf-8"))) client.close()
程序运行结果:
标签:tmp,Socket,0.0,编程,server,client,data,socket From: https://www.cnblogs.com/longlyseul/p/18171040