socket 编程实验
实验内容
1.编写一个基于UDP协议的客户机与服务器程序,实现相互通讯。
服务器端:
from socket import *
host = '10.100.118.128'
port = 60000
addr = (host, port)
s = socket(AF_INET, SOCK_DGRAM)
s.bind(addr)
print('等待客户端连接...')
while True:
data, addr = s.recvfrom(1024)
print(str(addr) + ':' + str(data.decode('utf-8')))
msg = '收到。'
s.sendto(msg.encode('utf-8'), addr)
s.close()
客户端
from socket import *
host = '10.100.118.128'
port = 60000
addr = (host, port)
s = socket(AF_INET, SOCK_DGRAM)
while True:
msg = input('向服务端发送:')
s.sendto(msg.encode('utf-8'), addr)
data, addr = s.recvfrom(1024)
print(addr, ':', data.decode('utf-8'))
s.close
2.编写一个基于TCP协议的客户机与服务器程序,实现相互通讯。 服务器端:
import socket
ip_port = ('10.100.118.128', 60001)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(5)
print('server waiting...')
conn, addr = sk.accept()
print('链接成成功, 客户端为:', addr)
while True:
client_data = conn.recv(1024)
print('[收到客户端数据]:' + client_data.decode('utf-8'))
if client_data == 'q':
break
msg = input('回复客户端:>>>')
conn.sendall(msg.encode('utf-8'))
conn.close()
sk.close()
客户端:
import socket
ip_port = ('192.168.2.102', 60000)
sk = socket.socket()
sk.connect(ip_port)
while True:
msg = input('向服务端发送:')
sk.sendall((msg.encode('utf-8')))
if msg == 'q':
break
server_reply = sk.recv(1024)
if not server_reply:
break
print('[收到服务端数据]:' + server_reply.decode('utf-8'))
sk.close()
|