python網路程式設計

2022-03-25 17:38:14 字數 1683 閱讀 7112

#testser.py

#coding=utf-8

from socket import *

from time import ctime

host = ""

port = 50000

bufsiz = 1024

addr = (host,port)

# 套接字定義方法:socket(socket_family,socket_type,protocol = 0)

# 套接字有兩種:基於檔案的af_unix(af_local為公升級版)和基於網路的af_inet

# 每一種套接字都可以分為面向連線的sock_stream、無連線的sock_dgram

tcpserversock = socket(af_inet,sock_stream)

# 繫結位址(主機名,埠)到套接字

tcpserversock.bind(addr)

# listen()表示最多允許多少個連線進來,而後的將被拒絕掉。

tcpserversock.listen(5)

while true:

print "waiting for connection..."

# accept() -> (socket object, address info) wait for an incoming connection.

# return a new socket representing the connection, and the address of the client.

# for ip sockets, the address info is a pair (hostaddr, port).

tcpclientsock,addr = tcpserversock.accept()

print "...connected from:",addr

while true:

# recv(buflen[, flags]) -- receive data

data = tcpclientsock.recv(bufsiz)

if not data:

break

tcpclientsock.send('[%s] %s'% (ctime(),data))

if data == '':

tcpclientsock.close()

tcpserversock.close()

#testcli.py

from socket import *

host = "127.0.0.1"

port = 50000

bufsize = 1024

addr = (host,port)

socketclient = socket(af_inet,sock_stream)

socketclient.connect(addr)

while true:

data = raw_input('>')

if not data:

break

socketclient.send(data)

data = socketclient.recv(bufsize)

if not data:

break

print data

socketclient.close()

python網路程式設計 TCP網路程式設計

tcp程式設計 客戶端 import socket 1 套接字 tcp socket socket.socket socket.af inet,socket.sock stream 2 建立鏈結 tcp socket.connect 172.27.35.1 8080 3 傳送資訊 tcp socke...

python 網路程式設計

今天晚上學習了一下python的網路程式設計,實現了client向server傳送資料,server反饋資訊 python 3.3 版本 server from socket import class tcpserver object def init self,serverport self.se...

python網路程式設計

網路通訊是計算機之間的程序之間的通訊。tcp程式設計 tcp連線建立是雙向通道,客戶端與服務端都可以給對方傳送資料。建立tcp連線時,主動發起連線的叫客戶端,被動響應連線的叫服務端。建立乙個tcp的socket連線 用socket family,type 建立套接字獲得socket物件。family...