socket作为服务端
直接上代码
static Socket mSocket;
static initSocket() async{
String host="192.168.1.6";
int port=50001;
var server=await ServerSocket.bind(host, port);
await for(var socket in server) {
socket.listen(dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError:false);
mSocket=socket;
//将向socket客户端发送命令传到写方法里进行转换
dataWrite(***);
//周期定时器
setTimeStart();
}
}
///发送命令
static void dataWrite(data) async{
mSocket.add(***);// ***是list<int>格式的数据
//也有mSocket.write()等方法,挑选适合的放松方式
}
///接收报文
static void dataHandler(data){
try {
print('接收到的数据${data}');
if(data is List) {
print('is List');
} else if (data is int) {
print('${data} is int');
} else if (data is double) {
print('${data} is double');
} else {
print('${data} is other type');
}
} catch (e) {
print(e);
}
mSocket.flush();
}
///socket捕获异常
static void errorHandler(error, StackTrace trace){
print("-***********"+error);
}
///socket关闭处理
static void doneHandler(){
mSocket.destroy();
}
socket作为客户端
监听的方法与服务端是一样的
直接上代码:
await Socket.connect(host,port).then((Socket socket) {
mSocket = socket;
mSocket.listen(dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError:false
);
if(socket!=null){
dataWrite(***);
}
}).catchError((e) {
print("无法连接:$e");
});