最近寫點小東西,要用到socket伺服器和客戶端,用python實現起來非常的方便。
貼點**
首先:引用必要的包
import thread接下來定義埠號和位址from socket import *
from time import ctime
host = ''然後是定義乙個socket物件並把socket物件繫結到剛才定義的位址add上port = 8888 #埠號
bufsize = 200000 #緩衝區大小
add = (host,port)
sersock = socket(af_inet,sock_stream)接下來就是重點了sersock.bind(add)
sersock.listen(10)
while true:在這個迴圈中接收和傳送資料,都是以資料流的形式來傳送。print 'waiting for connecting....'
clisock,addr = tcpsersock.accept()
print 'connected from:',addr
def priword():
while true:
data = clisock.recv(bufsize)
if data:
print data,'\n>』,
thread.start_new_thread(priword,())
while true:
reword = raw_input('>')
if not reword:
break
tcpclisock.send(reword)
clisock.close()
if not raw_input('\nenter out :'):
break
sersock.close()
接收端的**如下:
import threadfrom socket import *
host = 'localhost'
port = 8888
bufsiz = 20000
addr = (host,port)
clisock = socket(af_inet,sock_stream)
clisock.connect(addr)
print 'enter out!'
def priword():
while true:
data = clisock.recv(bufsiz)
if data:
print ':',data,'\n>',
thread.start_new_thread(priword,())
while true:
data = raw_input('>')
if not data:
break
clisock.send(data)
clisock.close()
python socket 簡單程式設計
伺服器端 import socket s socket.socket host socket.gethostname port 1234 s.bind host,port s.listen 5 while true c,addr s.accept print got connection from ...
python socket簡單的c s示例
客戶端和服務端其實是對等的。只不過服務端是bind乙個位址,客服端是connect乙個位址。另外服務端需要呼叫listen 函式使得服務端可以接受連線請求。send,sendall,recv等等是兩邊都可以用的。下面是示例。server.py import socket s socket.socke...
Python Socket寫的簡單Server
一 python server 是藍色部分,注釋為黑色字型 color blue usr bin python import socket import re import os color 第一步是建立socket物件。呼叫socket建構函式 socket socket.socket famil...