網絡編程--python實現 簡單的服務端和客戶端

python進行網絡編程非常簡單,下面展示的就是簡單的一個例子

python實現服務端:接收鏈接後,由有個線程處理後續工作。接收客戶端發來的消息,並作出應答。

#socket server demo
#file name sockServerDemo.py

import socket
import sys
from thread import *

host=''
port=5000

##tcpIP='localhost'
##tcpPort=17800

sock=socket.socket(socket.AF_INET ,socket.SOCK_STREAM )
print 'sock created!'
try:
    sock.bind((host,port))
except socket.error,msg:
    print 'Bind failed. Error Code: '+str(msg[0])+' Message '+msg[1]
    sys.exit()

print 'socket bind complete'

sock.listen(10)
print 'socket now listening'


#function for handling connections. This is a thread
def clientthread(conn):
    #conn.send('welcom to the server!')
    while True:
        data=conn.recv(1024)
        #the file is to the end
        if not data:
            break
        f=file('recvData.txt','a')
        f.write(data)
        conn.sendall('ack')
        print data
    f.close()
    conn.close()
    
while True:
    conn,addr=sock.accept()
    #print the addr and port
    print 'Connect with '+addr[0]+':'+str(addr[1])
    #create a thread to deal with connected connection
    start_new_thread(clientthread,(conn,))

#sock.close()
客戶端程序:

客戶端連接服務端,然後向服務端發送簡單的一條消息,並等待服務端的應答。

#socket client demo
#file name sockClientDemo.py

import socket
import sys
try:

    #creat a socket
    sock=socket.socket(socket.AF_INET , socket.SOCK_STREAM )
except socket.error,msg:
    print 'Failed to create socket.Error code:'+str(msg[0])+',Errot message:'+msg[1]
    sys.exit()

print 'sock is created successly!'

host='localhost'
port=5000
try:
    remote_ip=socket.gethostbyname(host)
except socket.gaierror:
    print 'hostname could not be resolved, exiting'
    sys.exit()

print 'IP of '+host+' is '+remote_ip

#connect to the server
sock.connect((remote_ip,port))
print 'sock connect to '+host+' on ip '+remote_ip
print 'port=%d'%port

#send data
message='hello, I am the client'

try:
    sock.sendall(message)
except socket.error:
    print 'Send failed'
    sys.exit()
print 'Message send successfully'

#read data back from server
reply=sock.recv(1024)
print reply

sock.close()



發佈了20 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章