Receive byte array from server to client? BinaryReader / BinaryWriter error?

2.6k Views Asked by At

Hi i'm a newbie in c# and doing server and client for sharing text file via tcp/ip socket connection. I used the BinaryReader / BinaryWriter to upload from client to server but stucking from server to client: From client to server:

Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var stream = new MemoryStream();
                var writer = new BinaryWriter(stream);
                writer.Write(fileName);
                writer.Write(authorName);
                writer.Write(fileContent);
                var data = stream.ToArray();  // send this data array to server
                clientSock.Connect("192.168.7.48", 9050); // targets machine ip add and port num
                clientSock.Send(data);
                writer.Dispose();
                stream.Dispose();
                clientSock.Close();

In server:

public void ReadCallBack(IAsyncResult ar) {

    String content = String.Empty;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    bytesRead = handler.EndReceive(ar);
    System.Diagnostics.Debug.WriteLine("Error asshole-0");
   if (bytesRead > 0)
   {
       if (flag == 0)
       {
           var stream = new MemoryStream(state.buffer);
           var reader = new BinaryReader(stream);
           fileName = reader.ReadString();
           authorName = reader.ReadString();
           fileContent = reader.ReadString();
           reader.Dispose();
           stream.Dispose();
           flag++;
           Console.Write(fileName + authorName);
           Console.Write(fileContent);
       }
       string path = @"C:\"+fileName;

       StreamWriter sw = new StreamWriter(path);
       sw.Write(fileContent);
       sw.Close();
       sw.Dispose();
       SqlCmd();
   }
   else
   {
       Invoke(new MyDelegate(LabelWrite));
   }

}

stream.Dispose();

Now i try to use the same way from server to client but got error

var stream = new MemoryStream(state.buffer);
var reader = new BinaryReader(stream);

stateObject is error?

2

There are 2 best solutions below

0
On

Remember and Flush the streams after you write them. From the snippets you have shared so far it doesn't look like there's a flush.

Have a look at the Stream Flush docs

0
On

PROBLEM:It may be that the whole data can't be read at once because socket receive data in buffers. SOLUTION:have you think about what is the use of byteread when handler.EndReceive(ar)is called.It tells you about the data read yet means you have to check whether you have received the whole data and if yes then continue to convert it to string.

    Public Class State
    Public CLient As Net.Sockets.Socket
    Public Const BufferConst As Integer = 100
    Public TmpBuffer(BufferConst) As Byte
    Public sb As New System.Text.StringBuilder
End Class

Public Sub SendText(txt As String, socket As Net.Sockets.Socket)
    socket.Send(System.Text.Encoding.UTF32.GetBytes(txt + "•"))
End Sub

Public Sub ReadData(ar As IAsyncResult)
    Dim state As State = ar.AsyncState
    Try
        Dim read As Integer = state.CLient.EndReceive(ar)
        If read > 0 Then
            state.sb.Append(System.Text.Encoding.UTF32.GetChars(state.TmpBuffer))
            If state.sb.ToString.IndexOf("•") > 0 Then
                'All data have been recived
                Console.WriteLine(state.sb.ToString())
            Else
                ' Not Complete Start it again
                state.CLient.BeginReceive(state.TmpBuffer, 0, state.BufferConst, Net.Sockets.SocketFlags.None, New AsyncCallback(AddressOf ReadData), state)
            End If
        End If
    Catch ex As Exception
        Console.Write("Read Error")
    End Try
End Sub