2017-07-12 18:51:50git
blog
github
網絡編程有常見的tcp,udp 連接github
這是一個簡單的tcp s/c 代碼例子編程
# -*- coding:utf-8 -*- """ socket server""" import socket PORT = 8080 HOST = 'localhost' BUFSIZE = 1024 ADDR = (HOST, PORT) tcpClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpClient.connect(ADDR) while True: data = input("輸入你的信息>") if not data: break tcpClient.send(data.encode('utf-8')) data = tcpClient.recv(BUFSIZE) if not data: break print(data) tcpClient.close()
# -*- coding:utf-8 -*- """ socket 編程""" import socketserver import socket import time PORT = 8080 HOST = 'localhost' BUFSIZE = 1024 ADDR = (HOST, PORT) tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServer.bind(ADDR) tcpServer.listen(5) while True: print('waiting for the connection ....') tcpCliSock, addr = tcpServer.accept() print('coonnect from :', addr) while True: data = tcpCliSock.recv(BUFSIZE) if not data: break tcpCliSock.send(('[%s] %s' % (time.time(), data)).encode('utf-8')) print(('這是客戶端發送的信息:[%s] %s' % (time.time(), data)).encode('utf-8')) tcpServer.close()