一、windows
socketTool
SocketTool工具(模拟开发板)和基于socket的java服务器(TCP/IP协议)开发
二、linux
server:
import socket
import os
server = socket.socket()
server.bind(('localhost',6971)) #绑定要监听地址和端口 如果是监听所有
server.listen(5) #监听
print("我要开始等电话了")
while True:
conn, addr = server.accept() # 等电话打进来 conn:服务端生成的实例,接受新实例,addr:客户端的地址
# conn就是客户端连过来而在服务器端为其生成的一个连接实例
print(conn, addr)
print("电话来了")
# count = 0
while True:
data = conn.recv(1024) #8192
print("recv:",data)
if not data: ###如果不判断,当client断开之后,server 就会死循环接受空数据.
print("client has lost...")
break
# conn.send(data.upper())
res = os.popen(data.decode("utf-8")).read()
print(len(res))
if len(res)==0:
res="res is empty"
# res=b"res has empty"
#res = os.popen(data).read() ###如果这么写就会报错。
'''
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/day8/sockserver.py", line 22, in <module>
res = os.popen(data).read()
File "D:\Python\Python36-32\lib\os.py", line 968, in popen
raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
TypeError: invalid cmd type (<class 'bytes'>, expected string)
'''
conn.send(str(len(res.encode())).encode("utf-8")) ##发送到client数据的size
client_ack = conn.recv(1024) ##这两行是为了防止粘包
print("准备发送了",client_ack.decode("utf-8"))
conn.send(res.encode("utf-8"))
# conn.send(res) ###如果这么写就会报错
'''
如果不decode("utf-8")
conn.send(res)
TypeError: a bytes-like object is required, not 'str'
'''
# count+=1
# if count >10:break
server.close()
client:
#-*-coding:utf-8-*-
import socket
client=socket.socket()#默认famliy=AF_INET(ipv4)地址簇 type=SOCK_STREAM (tcp/ip) 声明socket类型,同时生成socket连接对象
client.connect(("localhost",6971))
while True:
msg=input("请输入:").strip() #不能发送空数据
if len(msg)==0:continue #如果msg长度为0,就继续 ,重新发
client.send(msg.encode("utf-8")) #3.x 只能发bytes类型数据,只能接收ASCII数据,汉字不行,要发汉字只能编码成utf-8格式
data=client.recv(102400) #收102400字节数据
print(data.decode("utf-8")) #bytes类型打印出来要解码
client.close()
或:
netcat?
tcpdump?
https://www.cnblogs.com/gildoringlorin/p/3948809.html