#網絡編程

網絡編程

2017-07-12 18:51:50git

blog
github
網絡編程有常見的tcp,udp 連接github

tcp 面向鏈接的,就像打電話必需要一來一往的作出迴應

udp 是不面向連接的, 不須要作出迴應

這是一個簡單的tcp s/c 代碼例子編程

client.py

# -*- 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()

server.py

# -*- 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()

http://47.93.151.113/media/uploads/2017/07/12/screen-shot-2017-07-12-at-64838-pm.png

相關文章
相關標籤/搜索