A simple client/sever code. Please have a look.

shafaatmosvi

New member
Joined
Nov 6, 2012
Messages
2
Programming Experience
3-5
Server Code:
Imports System
Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports Microsoft.VisualBasic


Public Class Form1


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")


        Dim server As New TcpListener(localAddr, 55556)
        server.Start()
        Dim client As TcpClient = server.AcceptTcpClient()
        Dim networkStream1 As NetworkStream = client.GetStream()
        Dim bytes(client.ReceiveBufferSize) As Byte
        Dim dataReceived As String
        While True
            networkStream1.Read(bytes, 0, CInt(client.ReceiveBufferSize))          
            dataReceived = Encoding.ASCII.GetString(bytes)
        End While
    End Sub
End Class

Client Code:
Imports System
Imports System.Net.Sockets
Imports System.Net
Imports System.Text
Imports Microsoft.VisualBasic


Public Class Form1


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


            Dim tcpClient1 As New System.Net.Sockets.TcpClient()
            tcpClient1.Connect("127.0.0.1", 55556)
            Dim networkStream2 As NetworkStream = tcpClient1.GetStream()
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("hello!")
            TextBox1.Text = sendBytes(0)
            networkStream2.Write(sendBytes, 0, sendBytes.Length)
    End Sub
End Class





The client works fine, but the server has some read issues with the network stream. It gets stuck with this line "networkStream1.Read(bytes, 0, CInt(client.ReceiveBufferSize))" and never gets the data that client sends it and in vain keeps waiting for it. What is the problem here? Please, help. Thanks.
 
Last edited by a moderator:
Are you sure that it never receives the data? You have that Read call in an infinite loop so if it successfully data once it will go straight back to that Read call and try to read again. You're only sending data once so it will definitely block indefinitely on the second Read call.
 
By the way, there are two issues with your Byte array. First, it is 1 Byte longer than the maximum amount of data you're trying to read. Secondly, you are converting the entire array to text even if the data received didn't fill the entire array.
 
Back
Top