网络编程

2017-07-12 18:51:50

blog
github
网络编程有常见的tcp,udp 链接

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


FIZLIN
514 声望8 粉丝

跟我走吧,天亮就出发


« 上一篇
##正则匹配
下一篇 »
UDP-python