最近了解python的socket编程,写了个小的例子
客户端代码:
#!/usr/bin/env python # -*- coding:utf-8 -*- import socket import logging def client_connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.connect(('127.0.0.1', 8080)) import time time.sleep(2) s.send("1") print '1::', s.recv(1024) s.close() if __name__ == '__main__': client_connect()
服务器端代码:
#!/usr/bin/env python # -*- coding:utf-8 -*- import socket import logging def listen(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 8080)) s.listen(5) while True: connection, address = s.accept() print 'connection:::', connection print 'address:::', address try: connection.settimeout(5) buf = connection.recv(1024) print 'buf::', buf if buf == '1': connection.send("welcome to server!") else: connection.send("please go out.") except socket.timeout: print 'time out' connection.close() if __name__ == '__main__': print 'begin...' listen() print 'end...'
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/8089.html