#服务器端
from socket import *
# 第二个参数改成SOCK_DGRAM则为udp
serverSocket = socket(AF_INET, SOCK_STREAM)
# 作为服务器端,需要绑定端口
serverSocket.bind(('',12345))
# socket对象默认是主动发送的,需要用listen()改为被动接收
serverSocket.listen(5)
# accept()返回(conn, address),conn为一个新的socket对象,address为链接另一端机器的地址信息
clientSocket,clientInfo = serverSocket.accept()
recvData = clientSocket.recv(1024)
print("%s:%s"%(str(clientInfo), recvData))
clientSocket.close()
serverSocket.close()
# 客户端
from socket import *
clientSocket = socket(AF_INET, SOCK_STREAM)
# 客户端socket对象发起链接请求
clientSocket.connect(("192.168.119.153", 12345))
# 客户端发送消息
clientSocket.send("hello,server")
# 客户端接收从服务器端发来的消息
recvData = clientSocket.recv(1024)
print("recvData:%s"%recvData)
clientSocket.close()