网络编程
2017-07-12 18:51:50
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://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。