(一)TCP连接方式
1.TCP服务端
import socket
#创建一个socket:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#绑定IP端口:
server.bind(('192.168.8.1', 8090))
#监听:
server.listen(5)
print('服务器启动成功......')
#等待连接:
clientSocket, clientAddress = server.accept()
print('客户端连接成功......')
count = 1
while True:
data = clientSocket.recv(1024) #接收数据
print('接收到来自%s的数据:%s' % (clientAddress, str(data.decode('utf-8'))))
info = input('服务器的回复:') #'第' + str(count) +'此回复:'
clientSocket.send(info.encode('UTF-8'))
count += 1
2.TCP客户端
import socket
if __name__ == '__main__':
#创建客户端:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#连接服务器:
client.connect(('192.168.8.1', 8090))
count = 0
while True:
data = input('请输入要发送的数据:')
count += 1
#发送数据:
client.send(data.encode('UTF-8'))
#接收数据:
info = client.recv(1024)
print('服务器说:%s' % info.decode('UTF-8'))
(二)UDP连接方式
1.UDP服务端
import socket
udpServer = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udpServer.bind(('192.168.8.1', 8070))
while True:
data, addr = udpServer.recvfrom(1024)
print('客户端说:', data.decode('UTF-8'))
info = input('回复客户端:')
udpServer.sendto(info.encode('UTF-8'), addr)
2.UDP客户端
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
data = input('请输入要发送的数据:')
#发送数据:
client.sendto(data.encode('UTF-8'), ('192.168.8.1', 8070))
#接收数据:
info = client.recv(1024).decode('UTF-8')
print('服务器说:', info)