python內的socket已經預設實現了tcp和udp兩種傳輸協議。
本文通過乙個簡單的例子記錄一下socket的簡單使用方法。
實現:客戶端和服務端通過tcp協議通訊,客戶端向服務端傳送訊息,服務端接收訊息後新增 「 too !」 字串後返回給客戶端,客戶端可以主動斷開連線。
服務端**
import socket
import threading
# af_inet表示ipv4位址型別, af_inet6表示ipv6位址型別
# sock_stream: 表示傳輸協議型別是tcp,sock_dgram:表示傳輸協議型別是udp
socket_server = socket.socket(socket.af_inet, socket.sock_stream)
# 設定是否復用,true表示復用
socket_server.setsockopt(socket.sol_socket, socket.so_reuseaddr,
true
)hostname = socket.gethostname(
)ip = socket.gethostbyname(hostname)
port =
9000
addr =
(ip, port)
socket_server.bind(addr)
# 設定監聽, 128: 表示最大等待的連線個數
socket_server.listen(
128)
defhandle_client
(socket_client: socket.socket)
:while
true
: recv_data = socket_client.recv(
1024
)if recv_data:
recv_content = recv_data.decode(
"utf-8"
)print
("接收客戶端的資料為:"
, recv_content)
# 傳送資料
socket_client.send(
(recv_content +
" too !"
).encode(
"utf-8"))
else
:print
("客戶端下線了"
)break
while
true
:(socket_client, addr_client)
= socket_server.accept(
) sub_thread = threading.thread(target=handle_client, args=
(socket_client,))
# 設定守護主線程
sub_thread.setdaemon(
true
) sub_thread.start(
)
客戶端**
import socket
import time
socket_client = socket.socket(socket.af_inet, socket.sock_stream)
hostname = socket.gethostname(
)ip = socket.gethostbyname(hostname)
port =
9000
addr =
(ip, port)
socket_client.connect(addr)
exit_list =
["byebye"
,"exit"
]while
true
: msg =
input
("請輸入:"
)if msg in exit_list:
socket_client.close(
)break
msg_data = msg.encode(
"utf-8"
) socket_client.send(msg_data)
recv_data = socket_client.recv(
1024
) recv_msg = recv_data.decode(
"utf-8"
)print
(recv_msg)
現在我們已經對socket有所了解了,然後讓我們嘗試使用socket去實現靜態web伺服器
服務端 客戶端Socket通訊
服務端 using system using system.collections.generic using system.net using system.net.sockets using system.text using system.text.regularexpressions usi...
socket 服務端於客戶端
usr bin env python coding utf 8 time 2017 8 23 15 33 author mr zhang site file 服務端.py software pycharm from socket import import subprocess,struct,jso...
socket實現服務端與客戶端的通訊
伺服器端程式 cpp view plain copy include winsock2.h pragma comment lib,ws2 32.lib include using namespace std intmain intargc,char argv 建立套接字 sserver socket...