python网络编程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python网络编程相关的知识,希望对你有一定的参考价值。
1、python的网络编程
(1)、服务器端代码:
#!/usr/bin/python #_*_coding:utf-8_*_ import socket #导入socket模块,socket模块里面有socket类 sk = socket.socket() ip_port = (‘127.0.0.1‘, 9919) sk.bind(ip_port) sk.listen(5) while True: conn, address = sk.accept() conn.send(‘hello‘) flag = True while flag: data = conn.recv(1024) print data if data == ‘exit‘: flag = False conn.send(‘sb‘) conn.close()
(2)、客户端代码:
#!/usr/bin/python #_*_coding:utf-8_*_ import socket client = socket.socket() ip_port = (‘127.0.0.1‘, 9919) client.connect(ip_port) while True: data = client.recv(1024) print data inp = raw_input(‘client:‘) client.send(inp) if inp == ‘exit‘: break
(3)、运行结果
服务器端:
客户端:
这种是简陋的通信模式,但是基本可以实现了;
2、python的TCP通信
(1)、服务器端代码:
#!/usr/bin/python #_*_coding:utf-8_*_ from socket import * from time import ctime host = ‘192.168.1.112‘ port = 8810 buffer = 1024 addr = (host, port) ser = socket(AF_INET, SOCK_STREAM) ser.bind(addr) ser.listen(5) while True: print ‘waiting for connection....‘ cli,addr = ser.accept() print ‘.....connected from : ‘, addr while True: data = cli.recv(buffer) print ‘client >‘, data if data == ‘exit‘: break cli.send(‘%s %s‘ % (ctime(), data)) cli.close() ser.close()
(2)、客户端代码:
#!/usr/bin/python #_*_coding:utf-8_*_ from socket import * host = ‘192.168.1.112‘ port = 8810 buffer = 1024 addr = (host, port) cli = socket(AF_INET, SOCK_STREAM) cli.connect(addr) while True: data = raw_input(‘> ‘) if data == ‘exit‘: break cli.send(data) data = cli.recv(buffer) print data cli.close()
(3)、运行结果
服务器端:
客户端:
3、python的UDP通信
(1)、服务器端:
#!/usr/bin/python #_*_coding:utf-8_*_ from socket import * from time import ctime host = ‘192.168.1.112‘ port = 8812 buffer = 1024 addr = (host, port) ser = socket(AF_INET, SOCK_DGRAM) ser.bind(addr) print ‘waiting for message :‘ while True: data, addr = ser.recvfrom(buffer) print ‘client :‘, data ser.sendto(‘%s %s‘ % (ctime(), data), addr) ser.close()
(2)、客户端
#!/usr/bin/python #_*_coding:utf-8_*_ from socket import * host = ‘192.168.1.112‘ port = 8812 buffer = 1024 addr = (host, port) cli = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input(‘> ‘) if data == ‘exit‘: break cli.sendto(data, addr) data, addr = cli.recvfrom(buffer) print data cli.close()
(3)、运行结果
服务器端:
客户端:
本文出自 “11586096” 博客,请务必保留此出处http://11596096.blog.51cto.com/11586096/1867227
以上是关于python网络编程的主要内容,如果未能解决你的问题,请参考以下文章