您好,登錄后才能下訂單哦!
背景:每一個語言都會有入門的helloworld
內容:看完網絡編程的基礎知識,知道原來網絡編程也有小練習
概述:Echo,Chat,Proxy
網上有專門的練習。不管是UNIX網絡編程還是其他的書籍都會有相關的舉例
Echo,chat,Proxy在這里統一再現Python的實現,主要是Python的比較簡單,稍后也會補充一下PHP的swoole
Echo:
import os,sys,platform
import BaseHTTPServer
from SocketServer import ThreadingMixIn
import urllib,urllib2
import shutil
import re
import time
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
f = StringIO()
f.write(self.path)
length = f.tell()
f.seek(0)
self.response(length)
if f:
shutil.copyfileobj(f,self.wfile)
f.close()
def response(self,length):
self.send_response(200)
self.send_header("Content-type","text/html")
self.send_header("Content-Length",str(length))
self.end_headers()
class ThreadingServer(ThreadingMixIn,BaseHTTPServer.HTTPServer):
pass
if __name__ =="__main__":
serveraddr = ("",int(sys.argv[1]))
print "LISTEN Port(%s)" % (int(sys.argv[1]))
srvr = ThreadingServer(serveraddr,SimpleHTTPRequestHandler)
srvr.serve_forever()
Chat:
import socket,select
def broadcast_data(sock,message):
for socket in CONNECTION_LIST:
if socket != server_socket and socket !=sock:
try:
socket.send(message)
except:
socket.close()
CONNECTION_LIST.remove(socket)
if __name__ =='__main__':
CONNECTION_LIST = []
RECV_BUFFER = 4096
HOST = '0.0.0.0'
PORT = 3446
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_socket.bind((HOST,PORT))
server_socket.listen(10)
CONNECTION_LIST.append(server_socket)
print "Chat server started on port {}"+str(PORT)
while True:
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
if sock ==server_socket:
sockfd,addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print ("Client (%s,%s) connected" % addr)
broadcast_data(sockfd,"[%s:%s] entered room\n"% addr)
else:
try:
data = sock.recv(RECV_BUFFER)
if data:
broadcast_data(sock,"\r"+'<'+str(sock.getpeername())+'>'+data)
except:
broadcast_data(sock,"Client (%s,%s) is offline"% addr)
print ("Client (%s,%s) is offline"% addr)
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
聊天的客戶端也是一樣的
Chat-Client:
import socket,select,string,sys
def prompt():
sys.stdout.write("<you> ")
sys.stdout.flush()
if __name__=="__main__":
if(len(sys.argv)<3):
print "Usage: python chat_client.py host port"
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(2)
try:
s.connect((host,port))
except:
print ("Unable to connnect")
sys.exit()
print("Connected to remote host,Start send message")
prompt()
while True:
rlist = [sys.stdin,s]
read_list,write_list,error_list = select.select(rlist,[],[])
for sock in read_list:
if sock ==s:
data = sock.recv(4096)
if not data:
print '\nDisconnected from chat server';
sys.exit()
else:
sys.stdout.write(data)
prompt()
else:
msg = sys.stdin.readline()
s.send(msg)
prompt()
Proxy(好像當時碼的時候有小錯誤,反正就是連接兩邊的服務器,都接收過來,然后各自在轉發出去,來來回回,寫暈了)
import sys
import socket
import threading
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server.bind(local_host,local_port)
except:
print ("[!!] Failed to listen on %s:%d"% (local_host,local_port))
print ("[!!] Check for other listening sockets or correct permissions")
sys.exit(0)
print ("[*] Listening on $s:%d"% (localhos_host,local_port))
server.listen(5)
while True:
client_socket.addr = server.accept()
print ("[==>] Received incoming connnection from %s:%d"% addr[0],addr[1])
proxy_thread = threading.Thread(target = proxy_handler,args =(client_socket,remote_host,remote_port,receive_first))
proxy_thread.start()
def proxy_handler(client_socket,remote_host,remote_port,receive_first):
remote_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
remote_socket.connect((remote_host,remote_port))
if receive_first:
remote_buffer = receive_from(remote_socket)
hexdump(remote_buffer)
remote_buffer = response_handler(remote_buffer)
remote_socket.send(local_buffer)
print("[==>] Sent to remote")
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print("[<==] Sending %d bytes to local_host."%len(remote_buffer))
client.send(remote_buffer)
while True:
local_buffer = receive_from(client_socket)
if len(remote_buffer):
print ("[==>] Received %d bites from local_host" %len(local_buffer))
hexdump(local_buffer)
local_buffer = request_handler(local_buffer)
remote_socket.send(local_buffer)
print("[==>] Sent to remote")
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print("[<== ] Received %d bytes from remote." % len(remote_buffer))
hexdump(remote_buffer)
remote_buffer = response_handler(remote_buffer)
client.socket.send(remote_buffer)
print("[<==] Sent to Sent to local_host")
if not len(local_buffer) or not len(remote_buffer):
client_socket.close()
remote_socket.close()
print("[*] No more data.Closing connections")
break
def hexdump(src,length = 16):
result =[]
digits = 4 if isinstance(str,unicode) else 2
for i in xrange(0,len(src),length):
s = src[i:i+length]
hexa = b' '.join(["%0*x"%(digits,ord(x)) for x in s])
text = b''.join([x if 0x20 <= ord(0) <=0x7F else b'.' for x in s])
result.append(b'%04X %-*s %s'%(i,length*(digits + 1),hexa,text))
print(b'\n'.join(result))
def receive_from(connection):
buffer = ''
connection.settimeout(2)
try:
while True:
data = connection.recv(4096)
if not data:
break
buffer +=data
except:
pass
return buffer
def request_handler(buffer):
return buffer
def response_handler(buffer):
return buffer
def main():
if len(sys.argv[1:])!=5:
print("Usage:python proxy.py [localhos_host] [local_port] [remote_host] [remote_port] [receice_first]")
print("Example:python proxy.py 127.0.0.1")
sys.exit(0)
local_host = sys.argv[1]
local_port = int(sys.argv[2])
remote_host = sys.argv[3]
remote_port = sys.argv[4]
receive_first = sys.argv[5]
if 'True' in receive_first:
receive_first = True
else:
receive_first = False
server_loop(local_host,local_port,remote_host,remote_port,receive_first)
main()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。