tcp_server.py
from datetime import datetime
import socket
address=('localhost',6789)
max_size=1000
print('starting the server at',datetime.now())
print('waiting for a client to call.')
server=socket.socket(socket.af_inet,socket.sock_stream)
server.bind(address)
server.listen(5)#最多可以和5個客戶端鏈結
client,addr=server.accept()#接受第乙個到達的訊息
data=client.recv(max_size)#最大可接受的訊息長度
print('at',datetime.now(),client,'said',data)
client.sendall(b'are you talking to me?')
client.close()
server.close()
輸出:
starting the server at 2019-09-30 16:11:45.591459
waiting for a client to call.
at 2019-09-30 16:12:44.752999 said b』hey!』
tcp_client.py
import socket
from datetime import datetime
address=('localhost',6789)
max_size=1000
print('starting the client at',datetime.now())
#換成sock_stream來使用流協議tcp,使用connect來建立流
client=socket.socket(socket.af_inet,socket.sock_stream)
client.connect(address)
client.sendall(b'hey!')#tcp伺服器使用sendall()發生訊息
data=client.recv(max_size)
print('at',datetime.now(),'someone replied',data)
client.close()
輸出:
starting the client at 2019-09-30 16:12:44.752525
at 2019-09-30 16:12:44.753091 someone replied b』are you talking to me?』
udp_client.py:
import socket
from datetime import datetime
server_address=('localhost',6789)
max_size=4096
print('starting the client at',datetime.now())
client=socket.socket(socket.af_inet,socket.sock_dgram)
client.sendto(b'hey!',server_address)
data,server=client.recvfrom(max_size)
print('at',datetime.now(),server,'said',data)
client.close()
輸出:
tarting the client at 2019-09-30 16:22:39.000430
at 2019-09-30 16:22:39.000861 (『127.0.0.1』, 6789) said b』are you talking to me?』
udp_server.py:
from datetime import datetime
import socket
server_address=('localhost',6789)
max_size=4096
print('starting the server at',datetime.now())
print('waiting for a client to call.')
#埠的所有資料到套接字
server=socket.socket(socket.af_inet,socket.sock_dgram)
#af_inet表示建立乙個網際網路套接字,sock_dgram表示我們要傳送和接受資料報
server.bind(server_address)
data,client=server.recvfrom(max_size)
print('at',datetime.now(),client,'said',data)
server.sendto(b'are you talking to me?',client)
server.close()
輸出:
tarting the client at 2019-09-30 16:22:39.000430
at 2019-09-30 16:22:39.000861 (『127.0.0.1』, 6789) said b』are you talking to me?』
udp服務端 客戶端
個數 2的16次方 埠是資料發出或接收的入口 埠的目的 通過埠號找到對應的程序,完成資料的通訊 著名埠0 1023 這是建立了乙個基於udp協議的服務端 import socket todo 1.0 建立了乙個套接字,用來連線客戶端,傳送與接收資料 udp server socket.socket ...
TCP服務端和客戶端(1)
在陳述這個小例項之前,首先將mafile寫出來 makefile all client server all規則,他依賴於client和server規則 client tcp process.o tcp client.o client規則生成客戶端程式 gcc o client tcp proces...
TCP服務端和客戶端 8
在process.c的基礎上,繼續變換方案,將使用到readv和writev。並且使用到向量方式進行資料的傳送和接收。並在收到相應的訊號後釋放資源。include include include include include static struct iovec vs null,vc null ...