Python socket编程笔记

来源:互联网 发布:电气原理图 软件 编辑:程序博客网 时间:2024/06/05 02:00

Python socket编程笔记

来源于Python socket – network programming tutorial
客户端

#Socket client example in pythonimport socket   #for socketsimport sys  #for exit#create an INET, STREAMing sockettry:    # 分别代表IPv4和TCP连接    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)except socket.error:    print 'Failed to create socket'    sys.exit()print 'Socket Created'host = 'www.google.com';port = 80;try:    remote_ip = socket.gethostbyname( host )except socket.gaierror:    #could not resolve    print 'Hostname could not be resolved. Exiting'    sys.exit()#Connect to remote servers.connect((remote_ip , port))print 'Socket Connected to ' + host + ' on ip ' + remote_ip#Send some data to remote servermessage = "GET / HTTP/1.1\r\n\r\n"try :    #Set the whole string    s.sendall(message)except socket.error:    #Send failed    print 'Send failed'    sys.exit()print 'Message send successfully'#Now receive datareply = s.recv(4096)print replys.close()

服务端

import socketimport sysfrom thread import *HOST = ''   # Symbolic name meaning all available interfacesPORT = 8888 # Arbitrary non-privileged ports = socket.socket(socket.AF_INET, socket.SOCK_STREAM)print 'Socket created'#Bind socket to local host and porttry:    s.bind((HOST, PORT))except socket.error , msg:    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]    sys.exit()print 'Socket bind complete'#Start listening on sockets.listen(10)print 'Socket now listening'#Function for handling connections. This will be used to create threadsdef clientthread(conn):    #Sending message to connected client    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string    #infinite loop so that function do not terminate and thread do not end.    while True:        #Receiving from client        data = conn.recv(1024)        reply = 'OK...' + data        if not data:             break        conn.sendall(reply)    #came out of loop    conn.close()#now keep talking with the clientwhile 1:    #wait to accept a connection - blocking call    conn, addr = s.accept()    print 'Connected with ' + addr[0] + ':' + str(addr[1])    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.    start_new_thread(clientthread ,(conn,))s.close()
0 0
原创粉丝点击