以文本方式查看主题 - Foxtable(狐表) (http://foxtable.net/bbs/index.asp) -- 专家坐堂 (http://foxtable.net/bbs/list.asp?boardid=2) ---- [求助]TCP 连接 (http://foxtable.net/bbs/dispbbs.asp?boardid=2&id=144613) |
-- 作者:YDS -- 发布时间:2019/12/25 13:51:00 -- [求助]TCP 连接 需要读取串口服务器两路Socket的数据 服务器地址 192.168.0.254 一个端口是23 一个端口是24 这个需要怎么弄?
|
-- 作者:有点蓝 -- 发布时间:2019/12/25 14:07:00 -- 看看:http://www.foxtable.com/bbs/dispbbs.asp?BoardID=2&ID=28230&skin=0 开2个监听
[此贴子已经被作者于2019/12/25 14:07:16编辑过]
|
-- 作者:YDS -- 发布时间:2019/12/25 14:13:00 -- 怎么开两个监听?我需要把监听到的数据显示到界面上的?开两个客户端吗? |
-- 作者:有点蓝 -- 发布时间:2019/12/25 15:03:00 -- 开两个客户端 |
-- 作者:YDS -- 发布时间:2019/12/25 16:53:00 -- 有没有办法一个客户端开两个端口的监听 只要能判断出来接收到的数据是那个端口的就好 |
-- 作者:有点蓝 -- 发布时间:2019/12/26 8:19:00 -- 必须要new两个Socket对象,但是可以绑定到同一个回调事件中 |
-- 作者:YDS -- 发布时间:2019/12/26 11:55:00 -- 现在已经new两个Socket对象,也绑定到同一个回调事件中了 但是怎么分辨是那个Socket返回的数据 |
-- 作者:YDS -- 发布时间:2019/12/26 11:59:00 -- Private Sub ReceiveMsg() While True Dim packet As Byte() = New Byte(1024) {} Dim n As Integer = nStream.Read(packet, 0, packet.Length) Dim byt As Byte() = New Byte(n - 1) {} For i As Integer = 0 To n - 1 byt(i) = packet(i) Next ‘我想在这里能不能读取到是那个端口发送过来的数据 Functions.Execute("byte",byt) End While End Sub
|
-- 作者:有点蓝 -- 发布时间:2019/12/26 14:05:00 -- 改改源码 Public Sub New(ByVal ip As String, ByVal port As Integer, ByVal frm As Object) mainfrm = frm Dim server As IPAddress = IPAddress.Parse(ip) Dim tcp As New TcpClient() Try tcp.Connect(ip, port) Catch generatedExceptionName As Exception tcp = Nothing End Try If tcp Is Nothing Then MsgBox("无法连接服务器,请重试") Else Dim netStream As NetworkStream = tcp.GetStream() Dim loginInfo As String = System.Guid.NewGuid.ToString() & "|" & System.Net.Dns.GetHostName() \'唯一标识 和 机器码 Dim stream() As Byte = Encoding.Unicode.GetBytes(loginInfo) netStream.Write(stream, 0, stream.Length) \'往服务器发送登录信息 Dim buffer As Byte() = New Byte(50) {} netStream.Read(buffer, 0, buffer.Length) \'得到回发的信息 Dim connResult As String = Encoding.Unicode.GetString(buffer).Substring(0, 2) If connResult.Equals("OK") Then \'登录成功 nStream = netStream receiveThread = New Thread(New ParameterizedThreadStart(AddressOf ReceiveMsg)) receiveThread.Start(某端口号如24) Else MsgBox("登录失败……") Return End If End If End Sub \'\'\' <summary> \'\'\' 接受消息的线程执行体 \'\'\' </summary> Private Sub ReceiveMsg(port As Integer) msgbox(port) While True Dim packet As Byte() = New Byte(2) {} nStream.Read(packet, 0, packet.Length) Dim _cmd As String = String.Concat(packet(0), packet(1)) Select Case _cmd \'11状态,关闭客户端 Case "11" mainfrm.Close() If receiveThread IsNot Nothing Then receiveThread.Abort() End If nStream.Close() End Select End While End Sub |