python--socket
2016-01-20 11:59
591 查看
server端:
1.生成socket:socket(family,type)//family=socket.AF_INET or socket.AF_UNIX;;type=socket.SOCK_STREAM or socket.SOCK_DGRAM
2.绑定地址端口:bind((add,port))//eg.s.bind(('localhost,9090'))
3.监听:listen(backlog)//backlog指的是最大客户端连接数
4.接受链接:soc,add=accept()//注意,返回的那个soc用来处理数据,包括接受和发送
5.处理数据:1.接受data=soc.recv(len).decode()//len代表接受字符数;2.发送soc.send('xxx'.encode())
6.关闭:close()
client端:
1.生成socket:同server
2.连接:connect((add,port))//eg.s.connect(('localhost',9090))
3.处理数据:1.发送s.send('xxx'.encode);;2.接受s.recv(len).decode()
4.关闭:close()
一个实际的例子:
server:
import sys
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('localhost',8001))
s.listen(5)
i=0
while 1:
con,add=s.accept()
i=i+1
data=con.recv(1024).decode()
print('I am connected by NO.',i)
print('%s:%s'%(add,data))
con.send('Hello, Baby!^_^'.encode())
s.close()
client::
import sys
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('localhost',8001))
while 1:
s.send('Hello,Server!'.encode())
print('Hello,Server!')
s.close()
1.生成socket:socket(family,type)//family=socket.AF_INET or socket.AF_UNIX;;type=socket.SOCK_STREAM or socket.SOCK_DGRAM
2.绑定地址端口:bind((add,port))//eg.s.bind(('localhost,9090'))
3.监听:listen(backlog)//backlog指的是最大客户端连接数
4.接受链接:soc,add=accept()//注意,返回的那个soc用来处理数据,包括接受和发送
5.处理数据:1.接受data=soc.recv(len).decode()//len代表接受字符数;2.发送soc.send('xxx'.encode())
6.关闭:close()
client端:
1.生成socket:同server
2.连接:connect((add,port))//eg.s.connect(('localhost',9090))
3.处理数据:1.发送s.send('xxx'.encode);;2.接受s.recv(len).decode()
4.关闭:close()
一个实际的例子:
server:
import sys
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('localhost',8001))
s.listen(5)
i=0
while 1:
con,add=s.accept()
i=i+1
data=con.recv(1024).decode()
print('I am connected by NO.',i)
print('%s:%s'%(add,data))
con.send('Hello, Baby!^_^'.encode())
s.close()
client::
import sys
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('localhost',8001))
while 1:
s.send('Hello,Server!'.encode())
print('Hello,Server!')
s.close()
相关文章推荐
- python--杂
- 实践Python的爬虫框架Scrapy来抓取豆瓣电影TOP250
- [Python]不定长矩阵转置
- 37. Sudoku Solver leetcode python new season 2016
- python 异步io,asyncio
- Python算法题----玩转fibonacci数列
- [Python]FPG(FP-growth)算法核心实现
- python 字符串处理
- Python的爬虫包Beautiful Soup中用正则表达式来搜索
- Python学习笔记2016/1/20
- Python每日一练(2):找出html中的所有链接(Xpath、正则两个版本)
- 【LEETCODE】274-H-Index [Python]
- 36. Valid Sudoku leetcode Python new season 2016
- Python使用Beautiful Soup包编写爬虫时的一些关键点
- 转来的——python webdriver自动化测试初步印象——转来的
- Python制作爬虫抓取美女图
- Numpy——ndarray对象(1):创建数组
- 35. Search Insert Position leetcode Python 2016 new season
- 编写Python爬虫抓取豆瓣电影TOP100及用户头像的方法
- 自学Python十 爬虫实战三(美女福利续)