socket 套接字伺服器端和客戶端傳送資訊

2021-09-29 09:00:11 字數 2913 閱讀 3491

這是以前剛開始接觸python的時候寫的。記錄一下

伺服器端

import socket

import threading

host=

''port=

6889

defcilenthred

(conn,addr)

:print

("成功接受客戶端{}的連線:{}"

.format

(addr[0]

,str

(addr[1]

)))#伺服器向客戶端傳送資訊說明已經連線成功

msg=

'你已經成功連線到伺服器'

conn.sendall(

bytes

(msg,encoding=

"utf-8"))

while

true

: data=conn.recv(

1024

)print

("伺服器接受到的資料為{}"

.format

(str

(data,encoding=

"utf-8"))

) message=

'server>>{}'

.format

(str

(data,encoding=

"utf-8"))

conn.sendall(

bytes

(message,encoding=

"utf-8"))

chioce =

str(conn.recv(

1024

),encoding=

"utf-8"

)if chioce==

"exit"

: conn.close(

)break

else

:pass

try:

s=socket.socket(socket.af_inet,socket.sock_stream)

#繫結ip位址和埠號

s.bind(

(host,port)

)print

('成功繫結了ip位址,埠號為{}'

.format

(port)

)#伺服器建立監聽

s.listen(10)

print

("建立監聽模式"

)while

true

:#成功接收客戶端的連線,兵返回連線物件和位址

conn,addr=s.accept(

) t=threading.thread(target=cilenthred,args=

(conn,addr)

) t.start(

)except socket.error as msg:

print

("socket出現錯誤,錯誤為{}"

.format

(msg)

)finally

: s.close(

)

客戶端

import socket

import sys

host=

"localhost"

port=

6889

try:

s=socket.socket(socket.af_inet,socket.sock_stream)

print

('成功建立socket物件'

) s.connect(

(host,port)

)print

("成功連線到伺服器端"

) reply=

str(s.recv(

1024

),encoding=

"utf-8"

)print

("成功接受到伺服器返回的內容:{}"

.format

(reply)

)while

true

: message=

input

("請輸入要傳送到伺服器的資訊》"

) s.sendall(

bytes

(message,encoding=

"utf-8"))

print

("向伺服器傳送請求成功"

) reply1=

str(s.recv(

1024

),encoding=

"utf-8"

)print

("成功接受到伺服器返回的內容{}"

.format

(reply1)

) chioce=

input

("是否繼續輸入?(y/n)"

)if chioce.lower()==

"y":

s.sendall(

bytes

("ok"

,encoding=

"utf-8"))

pass

else

: s.sendall(

bytes

("exit"

,encoding=

"utf-8"))

print

("輸入結束"

)break

except socket.error as msg:

print

("建立socket錯誤,錯誤為"

.format

(msg)

) sys.exit(-1

)finally

: s.close(

)

socket伺服器端

伺服器 include winsock2.h include string.h include stdio.h include time.h include stdarg.h include stdlib.h pragma comment lib,ws2 32 void errexit const ...

socket程式設計 10 實現迭代伺服器端和客戶端

前面的程式,不管伺服器端還是客戶端,都有乙個問題,就是處理完乙個請求立即退出了,沒有太大的實際意義。能不能像web伺服器那樣一直接受客戶端的請求呢?能,使用 while 迴圈即可。修改前面的回聲程式,使伺服器端可以不斷響應客戶端的請求。伺服器端 server.cpp include include ...

SOCKET伺服器端的操作

1 確定socket版本 word tsocketverno wsadata tverdata tsocketverno makeword 2,0 wsastartup tsocketverno,tverdata 2.建立乙個socket socket serversock serversock s...