python socket 服务器和客户端

817阅读 0评论2012-10-10 niexining
分类:Python/Ruby


点击(此处)折叠或打开

  1. import socket
  2. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3. port = input("port: ")
  4. sock.bind(('localhost', port))
  5. print "serving on port %s" %(port)
  6. sock.listen(1)

  7. while 1:
  8.     connection,address = sock.accept()
  9.     while 1:
  10.         print "receiving ..."
  11.         buf = connection.recv(1024)
  12.         if buf == '1': connection.send('welcome to server!')
  13.         elif buf == 'shutdown': connection.close();break
  14.         else: connection.send(buf);print buf

点击(此处)折叠或打开

  1. import socket
  2. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  3. port = input("port: ")
  4. sock.connect(('localhost', port))
  5. while 1:
  6.     data = raw_input("data to send: ")
  7.     if data == "quit":
  8.         sock.close()
  9.         break
  10.     sock.send(data)
  11.     print "receiving..."
  12.     datas = sock.recv(1024)
  13.     print datas

上一篇:窗体文件version2
下一篇:多线程socket客户端