【发布时间】:2014-06-10 16:07:57
【问题描述】:
好的,我猜这是一个非常基本的问题,我不确定我的代码有什么问题。我与另一个字符串 (ClientName) 连接的任何字符串/字符都没有显示。事实上,它只是删除了 ClientName 之后的任何其他字符。
代码如下:
公共子聊天()
While Link.Client.Connected
Try
NumberOfMessages = NumberOfMessages + 1 'Update number of clients.
Stream = Link.GetStream 'Get the stream from Socket.
Dim MessageIn, MessageOut As String
MessageIn = GetDataFromStream(Stream)
ClientName = GetClientName_Stream(MessageIn)
MessageBox.Show(ClientName & "****") 'Here **** is removed :-/
MainForm.UpdateMessage(ClientName & ">> " & MessageIn)
MessageOut = MessageIn 'Echo Back same message
SendDataFromStream(Stream, MessageOut)
Catch e As Exception
End Try
End While
End Sub
这是从收到的消息中提取名称的函数:
私有函数 GetClientName_Stream(ByVal msg As String) As String
Dim pos As Integer
pos = msg.LastIndexOf("$")
Dim name As String
name = msg.Substring(pos + 1)
Return name
End Function
客户端以这种格式发送消息:
Hello World$TheClientName
其中 TheClientName 是该客户端的名称。
这是 GetDataFromStream 函数:
私有函数 GetDataFromStream(Stream As NetworkStream) As String
Dim Buffer(2000) As Byte 'The buffer in which the data will be stored in form of Bytes.
Dim SizeOfData As Integer = Buffer.Length 'Link.ReceiveBufferSize 'The size of Buffer to read.
Dim TheData As String 'The Data received from Stream.
Stream.Read(Buffer, 0, SizeOfData) 'Read the Stream and store it in Buffer.
TheData = System.Text.Encoding.ASCII.GetString(Buffer) 'Create String from Buffer.
Return TheData
End Function
【问题讨论】:
-
我误解了这个问题,所以我删除了我之前的答案,并将添加一个新答案。
标签: vb.net string-concatenation tcpserver