首页 > 代码库 > python---tcp/ip网络编程

python---tcp/ip网络编程

重点总结:

服务端:一直运行(while true),监听运行所在机器(ip)某端口,多线程或多进程接收客户端的socket请求

客户端:主动发起请求,需求知道服务器的ip和端口

 

服务端:

# -*- coding:utf-8 -*-
import time
import socket
import threading
def tcplink(sock, addr):
print ‘Accept new connection from %s:%s...‘ % addr
sock.send(‘Welcome!‘)
while True:
data = http://www.mamicode.com/sock.recv(1024)
time.sleep(1)
if data =http://www.mamicode.com/= ‘exit‘ or not data:
break
sock.send(‘Hello, %s!‘ % data)
sock.close()
print ‘Connection from %s:%s closed.‘ % addr


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((‘127.0.0.1‘, 9999))
s.listen(5)
print ‘Waiting for connection...‘
while True:
# 接受一个新连接:
time.sleep(5)
print ‘sdasdasd‘
sock, addr = s.accept()
print sock
print addr
# 创建新线程来处理TCP连接:
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()

客户端:
# -*- coding:utf-8 -*-
import time
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect((‘127.0.0.1‘, 9999))
# 接收欢迎消息:
print s.recv(1024)
for data in [‘Michael‘, ‘Tracy‘, ‘Sarah‘]:
# 发送数据:
s.send(data)
print s.recv(1024)
s.send(‘exit‘)
s.close()
 

python---tcp/ip网络编程