python socket 簡單程式設計

2021-08-15 22:39:17 字數 1446 閱讀 3028

伺服器端 **:

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',addr

c.send('thank you for connecting')

c.close()

客戶端**

import socket

s= socket.socket()

host = socket.gethostname()

port = 1234

s.connect((host,port))

str = s.recv(1024)

print str

首先執行服務區端,然後執行 客戶端:伺服器端執行結果:

got connection from ('169.254.68.168', 58607)

got connection from ('169.254.68.168', 58610)

客戶端執行結果:

thank you for connecting
下面是測試,出錯的情況處理

只執行客戶端**,不執行伺服器端**

會得到如下結果:

將客戶端**,修改為如下模式:

import socket

s= socket.socket()

host = socket.gethostname()

port = 1234

try:

s.connect((host,port))

except socket.error, e:

print("socket connect error:%s" % e)

exit(1)

str = s.recv(1024)

print str

只執行客戶端**,不執行伺服器端**執行結果如下:

socket connect error:[errno 10061] 

process finished with

exit code 1

python socket簡單使用 一

匯入socket模組 import socket socket可以看做為乙個檔案,用乙個socket表示 開啟了乙個網路鏈結 開啟乙個socket需要知道目標計算機的ip位址和埠號 建立tcp連線是,自動發起連線的叫做客戶端,被動響應連線的叫做伺服器 新建乙個socket物件 原型 socket.s...

簡單的python socket程式設計

最近寫點小東西,要用到socket伺服器和客戶端,用python實現起來非常的方便。貼點 首先 引用必要的包 import thread from socket import from time import ctime接下來定義埠號和位址 host port 8888 埠號 bufsize 200...

Python socket 簡單示例程式

pyhton 的socket 通訊簡單方便,寫了乙個小例子,真的挺方便的 客戶端 import thread from socket import host 192.168.7.118 port 8888 bufsize 20000 addr host,port clisock socket af ...