客户端代码如下:
Private th As Threading.Thread
Private tcpc As System.Net.Sockets.TcpClient
Private Sub ConnectBt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectBt.Click
Try
tcpc = New System.Net.Sockets.TcpClient(TcpAddrTextBox.Text, CInt(TcpPortTextBox.Text))
th = New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf MyListen))
th.Start()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End Sub
Private Sub SendBt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendBt.Click
Try
Dim tcpStream As Net.Sockets.NetworkStream = tcpc.GetStream
Dim DataStr As String = MsgSendTextBox.Text
Dim reqStream As New IO.StreamWriter(tcpStream)
reqStream = New IO.StreamWriter(tcpStream)
reqStream.Write(DataStr)
reqStream.Flush()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End Sub
Private Sub MyListen()
Try
Dim ReadStream As IO.StreamReader
Dim Count As Integer
Dim i As Integer
Dim RecvStr As String
Dim tcpStream As Net.Sockets.NetworkStream
While True
tcpStream = tcpc.GetStream
ReadStream = New IO.StreamReader(tcpStream)
Dim Buf(1023) As Char
Count = ReadStream.Read(Buf, 0, 1024)
If Count > 0 Then
i = 0
RecvStr = ""
While i < Count
RecvStr += Buf(i)
i += 1
End While
MsgRecvRichTextBox.AppendText(RecvStr & Chr(10) & Chr(13))
End If
End While
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End Sub
服务器端代码如下:
Private th As Threading.Thread
Private tcpl As System.Net.Sockets.TcpListener
Private sSocket As System.Net.Sockets.Socket
Private Sub StartBt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartBt.Click
th = New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf MyListen))
th.Start()
End Sub
Private Sub MyListen()
Try
Dim ipAddress As System.Net.IPAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0)
tcpl = New System.Net.Sockets.TcpListener(ipAddress, CInt(TcpPortTextBox.Text))
tcpl.Start()
Dim RecvStr As String
Dim Count As Integer
Dim i As Integer
While True
RecvStr = ""
sSocket = tcpl.AcceptSocket()
Dim MyBuffer(1024) As Byte
Count = sSocket.Receive(MyBuffer)
If Count > 0 Then
RecvStr = ""
For i = 0 To Count - 1
RecvStr += Chr(MyBuffer(i))
Next
Dim Array() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(RecvStr)
sSocket.Send(Array, Array.Length, Net.Sockets.SocketFlags.None)
End If
End While
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
代码实现的功能很简单,客户端向服务器发送一段字符串,服务器收到后再发回来,但是不知道为什么客户端连接上以后,只能发送和接收一次,再次发送就没反应了,这过程tcpc并没有关闭连接啊,兄弟们帮忙看看是服务器的问题还是客户端的问题。