python简易socket

1.sever

'
#!/usr/bin/python
# -*- coding:utf-8 -*-

if __name__ == '__main__':
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8011))
sock.listen(5)
while True:
connection,address = sock.accept()
try:
connection.settimeout(5)
buf = connection.recv(1024)
if buf == '1':
connection.send('welcome to eqi.cc server!')
else:
mess = raw_input()
connection.send(mess)
except socket.timeout:
print 'time out'
connection.close()

2.client

'
#!/usr/bin/python
#-*- coding: UTF-8 -*-

if __name__ == '__main__':
import socket
while True:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8011))
# import time
# time.sleep(2)
sock.send('2')
print sock.recv(1024)
sock.close()

https://github.com/rongtian/scoket

496 views 2016-12-25