网络编程(三)
简单的网络通讯:
server端
import socket server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind(('127.0.0.1',8999)) server.listen(5) conn,addr = server.accept() while 1: form_msg = conn.recv(1024).decode('utf-8') #接收来自客户端的消息 print(form_msg) data = input('>>>') conn.send(data.encode('utf-8'))#进行回复 conn.close() server.close()
client:客户端
import socket client = socket.socket() client.connect(('127.0.0.1',8999)) while 1: data = input('>>>') client.send(data.encode('utf-8'))#给服务端进行发送消息 msg = client.recv(1024).decode('utf-8')#接收来自服务端的消息 print(msg) client.close()
循环通讯 :
server端:服务端
import socket server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind(('127.0.0.1',8999)) server.listen(5) while 1:#循环服务端的等待接入的这段代码 让服务器一直循环 conn,addr = server.accept() while 1: form_msg = conn.recv(1024).decode('utf-8') #接收来自客户端的消息 print(form_msg) data = input('>>>') conn.send(data.encode('utf-8'))#进行回复 conn.close() server.close()
client:客户端
import socket client = socket.socket() client.connect(('127.0.0.1',8999)) while 1: data = input('>>>') client.send(data.encode('utf-8'))#给服务端进行发送消息 msg = client.recv(1024).decode('utf-8')#接收来自服务端的消息 print(msg) client.close()