1.客户端
import socket client = socket.socket() //声明socket类型,同时生成socket对象 client.connect(("localhost",7000)) //连接地址和端口 client.send("nihao") //发送数据 data=client.recv(1024) //接受服务端返回的数据,只接受1024个字节 print ("recv:",data) //打印数据 client.close()
2.服务端
import socket server=socket.socket() server.bind(("localhost",7000)) server.listen() //监听 conn,addr=server.accept() //等待conn 就是客户端连过来在服务端生成的一个实例 print(conn,addr) data=server.recv(1024) print("recv:",data) conn.send(data.upper()) //data的数据变成大写输出。或者 print("recv:",data.upper()) server.close()