python socket编程

---恢复内容开始---

最近想练习用python写一个聊天的小程序,在使用socket的过程中遇到了种种困惑,好在一步步解决了问题。

学习socket,最开始练习了tcp的echo client 和echo server 参考了廖雪峰的python网络编程部分

tcpserver.py

 1 #usr/bin/python
 2 #-*- coding = utf-8 -*-
 3 from socket import *
 4 import threading,time
 5 
 6 HOST = '127.0.0.1'
 7 PORT = 5005
 8 BUFSIZ = 1024
 9 ADDR = (HOST,PORT) 
10     
11 def tcplink(sock,addr):
12     print 'Accept new connection from %s :%s.....' %addr
13     sock.send("Welcome")
14     while True:
15         data = sock.recv(1024)
16         time.sleep(1)
17         if data == 'exit' or not data :
18             break
19         sock.send('Hello ,%s! '% data)
20     sock.close()
21     print 'Connection from %s :%s closed ' %addr
22 
23 s = socket(AF_INET,SOCK_STREAM)
24 s.bind(ADDR)  
25 s.listen(5)
26 
27 while True:
28     print 'waiting for connection'
29     sock, addr = s.accept()
30     print 'conncting from :',addr31     t= threading.Thread(target =tcplink,args=(sock,addr)) #多线程实现
32     t.start()
33   

tcpclient.py

 1 #!usr/bin/env python 
 2 from socket import *
 3 
 4 HOST='127.0.0.1'
 5 PORT=5005
 6 BUFSIZE = 1024
 7 ADDR = (HOST,PORT)
 8 
 9 s = socket(AF_INET, SOCK_STREAM)
10 s.connect(ADDR)
11 print s.recv(1024)
12 while True:
13     data1 = raw_input('>')
14     s.send(data1)
15     if data1=='exit':
16         break
17     print s.recv(BUFSIZE)
18 s.close()

接着扩展程序 找到另一篇文章

http://www.cnblogs.com/hazir/p/python_chat_room.html

实现了一个简单的聊天程序,但是还是存在着很多问题,坑先放着以后过来添

 

posted on 2016-04-16 22:10  月尽西楼  阅读(280)  评论(0编辑  收藏  举报

导航