python编程--聊天小程序

用socket库编写:
--socket库的使用,聊天工具(一人一句)
  1. '''
  2. Created on 2013-10-3
  3. @author: casa
  4. '''
  5. import socket
  6. if  __name__=="__main__":
  7.     sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
  8.     print("create socket success");
  9.    
  10.     sock.bind(("localhost",4242));
  11.     print("bind socket success");
  12.    
  13.     sock.listen(5);
  14.     print("listen socket success");
  15.    
  16.     print("listen to client...");
  17.     conn, address=sock.accept();
  18.     print("get client: ");
  19.     print(address);
  20.        
  21.     print("\n\n\nstart chatting:\n");
  22.     while True:
  23.         szbuf=conn.recv(1024)
  24.         print("you: \n"+szbuf);
  25.        
  26.         if  szbuf=="0":
  27.             conn.send("exit");
  28.         else:
  29.             input_s=raw_input("me: \n");
  30.             print("wait for others enter...");
  31.             conn.send(input_s);
  32.            
  33.     conn.close();
  34.     print("end of service");

  1. '''
  2. Created on 2013-10-3
  3. @author: casa
  4. '''
  5. import socket
  6. if  __name__=="__main__":
  7.     sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  8.     sock.connect(("localhost",4242));
  9.    
  10.     print("\n\n\nstart chatting:\n");
  11.     while True:
  12.         print("me: ");
  13.         guess=raw_input('');
  14.         print("wait for others enter...");
  15.        
  16.         sock.send(guess);
  17.    
  18.         szbuf=sock.recv(1024);
  19.         print("you: \n"+szbuf);
  20.        
  21.     sock.close();
  22.     print("end of connect");

你可能感兴趣的:(python)