# TCP服务器 __author__ = ‘magicpwn‘ import socket import threading bind_ip = ‘0.0.0.0‘ bind_port = 9999 # 构造服务器套接字 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 套接字绑定主机、端口 server.bind((bind_ip, bind_port)) # 开始监听,监听最大连接数数量为5 server.listen(5) # 线程任务,处理请求,参数(客户端套接字) def handle_client(client_socket): while True: # 接受信息 request = client_socket.recv(1024) print "[*] Received: %s" % request ask = raw_input() # 发送信息 client_socket.send(ask) client_socket.close() # 主循环等待连接 while True: # 接受连接,和连接终端的信息 client, addr = server.accept() print "[*] Accepted Connecton from: %s:%d" % (addr[0], addr[1]) client_handler = threading.Thread(target=handle_client,args=(client,)) client_handler.start()
# TCP客户端 # -*- coding:utf-8 -*- __author__ = ‘magicpwn‘ import socket # tcp客户端 target_host = ‘127.0.0.1‘ target_port = 9999 # AF_INET是标准IPv4地址或主机名,SOCK_STREAM表示是TCP的方式 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立连接 client.connect((target_host, target_port)) # 发送数据 while True: ask = raw_input() client.send(ask) # 接收返回的数据,参数是buffersize. response = client.recv(4096) print response
本文出自 “magicpwn” 博客,请务必保留此出处http://magicpwn.blog.51cto.com/10497784/1689122
原文地址:http://magicpwn.blog.51cto.com/10497784/1689122