c# System.Net.Sockets =》TcpListener用法
程序员文章站
2022-03-22 14:21:27
开始运行 监听 处理事件 ......
private tcplistener _listener;
#region 初始化 listener public override void init() { try { devinfo.read(); var localaddr = ipaddress.parse(ip); var port = convert.toint32(port); _listener = new tcplistener(localaddr, port); } finally { statuschangedevent?.invoke(status); } } #endregion
开始运行
public override void start() { init(); _listener?.start(); task.factory.startnew(monittcpclientconnect); }
监听
private void monittcpclientconnect() { while (true) { try { var client = _listener.accepttcpclient(); task.factory.startnew(monitorrecvdata, client); } catch { _listener.stop(); _listener = null; return; } } }
处理事件
private void monitorrecvdata(object obj) { try { var tcpclient = obj as tcpclient; if (tcpclient == null) { return; } var buffer = new byte[1024];var stream = tcpclient.getstream(); while (true) { var count = stream.read(buffer, 0, buffer.length); if (count == 0) { throw new exception("客户端下线"); } var str = encoding.ascii.getstring(buffer, 0, count); } } catch { // ignored } }
上一篇: Go map定义的方式及修改技巧
下一篇: C#数据类型