tcp
tcp伺服器
from
socket
import*
from
time
import
ctime
host = ''
port =
12345
bufsize =
1024
addr = (host,port)
tcpsersock = socket(af_inet,sock_stream)
tcpsersock.bind(addr)
tcpsersock.listen(5)
while
true
'waiting for connection...'
tcpclisock, addr = tcpsersock.accept()
'connected from:'
,addr
while
true
:data = tcpclisock.recv(bufsize)
ifnot
data:
break
tcpclisock.send(
'[%s]%s'
%(ctime(),data))
tcpclisock.close()
tcpsersock.close()
tcp客戶端
from
socket
import*
host =
'localhost'
port =
12345
addr = (host,port)
bufsize = 1024
tcpclisock = socket(af_inet,sock_stream)
tcpclisock.connect(addr)
while
true
:data = raw_input(
'input:')if
notdata:
break
tcpclisock.send(data)
data = tcpclisock.recv(bufsize)
ifnot
data:
break
data
tcpclisock.close()
udpudp伺服器
from
socket
import*
from
time
import
ctime
host = ''
port =
12345
bufsize =
1024
addr = (host,port)
udpsersock = socket(af_inet,sock_dgram)
udpsersock.bind(addr)
while
true
'waiting for message...'
data, addr = udpsersock.recvfrom(bufsize)
udpsersock.sendto(
'[%s]%s'
%(ctime(),data),addr)
'received from and returned to :'
,addr
udpsersock.close()
udp客戶端
from
socket
import*
host =
'localhost'
port
= 12345
addr = (host,port)
bufsize =
1024
udpclisock = socket(af_inet,sock_dgram)
while
true
:data = raw_input(
'input:')if
notdata:
break
udpclisock.sendto(data,addr)
data,addr = udpclisock.recvfrom(bufsize)
ifnot
data:
break
data
udpclisock.close()
利用socketserver模組實現網路通訊
socketserver是標準庫中乙個高階別的模組。用於簡化網路客戶與伺服器的實現
socketservertcp伺服器
# -*- coding: cp936 -*-
from
socketserver
import
(tcpserver
astcp,streamrequesthandler
assrh)
from
time
import
ctime
host = ''
port =
1234
addr = (host,port)
#繼承streamrequesthandler
類class
myrequesthandler(srh):
#重寫方法
handle
defhandle(self):
'connected from :'
,self.client_address
data = self.rfile.readline()
self.wfile.write(
'[%s]%s'
%(ctime(),data))
tcpserver = tcp(addr,myrequesthandler)
'waiting for connection'
tcpserver.serve_forever()
socketservertcp客戶端
# -*- coding: cp936 -*-
from
socket
import*
host
= 'localhost'
port =
1234
addr = (host,port)
bufsize =
1024
while
true
:tcpclisock = socket(af_inet,sock_stream)
tcpclisock.connect(addr)
data = raw_input(
'輸入:')
ifnot
data:
break
tcpclisock.send(
'%s\n'
%data)
#如果沒有
'%s\n'
收不到,因為是一行行讀的
data = tcpclisock.recv(bufsize)
ifnot
data:
break
data
tcpclisock.close()
python網路程式設計入門
服務端 tcp服務端 import socket import threading 建立連線 defdata recv conn while true msg conn.recv 1024 接收客戶端的資訊 print 輸出 msg.decode defmsg send conn while tru...
python網路程式設計入門例子
import socket import threading import time s socket.socket 建立socket物件 host addr 192.168.137.1 根據自己電腦的ip位址而定 port 9090 s.bind host addr,port s.listen 5...
九 Python入門 網路程式設計
總共65535 216 個埠 知名埠 0 1023 80 http服務 21 ftp服務 動態埠 1024 65535 不固定分配某種服務 分類 a類 b類 c類 d類,區分什麼類看子網掩碼 dns 網域名稱解析器 注 127.0.0.1表示本機ip tcp 傳輸控制協議 通訊之前必須建立可靠的連線...