1. 按
在Python中socket.SOCK_DGRAM用于UDP通信,socket.SOCK_STREAM用于TCP通信
2. UDP案例源码
客户端可以向服务器端主动发送信息
2.1. 客户端
import socket
BUF_SIZE = 1024
server_addr = ('127.0.0.1', 8888)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
data = input('Please Input data > ')
client.sendto(data.encode(), server_addr)
data, addr = client.recvfrom(BUF_SIZE)
print("Data : ", data)
client.close()
2.2. 服务器端
import socket
BUF_SIZE = 1024
server_addr = ('127.0.0.1', 8888)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_addr)
while True:
print("waitting for data")
data, client_addr = server.recvfrom(BUF_SIZE)
print('Connected by', client_addr, ' Receive Data : ', data)
server.sendto(data, client_addr)
server.close()
2. TCP案例源码
客户端可以向服务器端主动发送信息,服务器端也可以主动向客户端发送信息
2.1. 客户端
import socket
import threading
def recvlink(client):
while True:
msg = client.recv(1024)
print('Ubuntu say: ' + msg.decode('utf-8'))
def main():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 1234
client.connect((host, port))
start_msg = client.recv(1024)
print(start_msg.decode('utf-8'))
t = threading.Thread(target=recvlink, args=(client,))
t.start()
while True:
sendmsg = input()
client.send(sendmsg.encode('utf-8'))
if sendmsg == 'quit':
break
client.close()
if __name__ == '__main__':
main()
2.2. 服务器端
import socket
import threading
def recv_msg(clientsocket):
while True:
recv_msg = clientsocket.recv(1024)
msg = recv_msg.decode('utf-8')
if msg == 'quit':
exit(0)
print('Win10 say: ' + msg)
def main():
socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1'
port = 1234
socket_server.bind((host, port))
socket_server.listen(5)
clientsocket, addr = socket_server.accept()
clientsocket.send('你现在已经连接上了服务器啦,我们来聊天吧!'.encode('utf-8'))
t = threading.Thread(target=recv_msg, args=(clientsocket,))
t.start()
while True:
reply = input()
clientsocket.send(reply.encode('utf-8'))
clientsocket.close()
if __name__ == '__main__':
main()
|