-2

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?

Cao Linh Truong
  • 253
  • 8
  • 20
  • 3
    Please some more specific error information, e.g. the exception thrown with a stack trace. – Martin Liversage Aug 10 '12 at 15:00
  • Provide the network code otherwise we cannot help you. – Security Hound Aug 10 '12 at 15:02
  • `BinaryReader.ReadString()` expects the whole string to be present in the buffer, prepended by its length. `ReadInt32()` expects four bytes to be present. A `Socket.Receive()` can receive a partial message, so either not the whole string can't be read or the int lacks one or more bytes. You'll have to buffer all input (i.e. store data between `Receive()` calls) until you start processing it. – CodeCaster Aug 10 '12 at 15:05

2 Answers2

3

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
Kshitij
  • 353
  • 3
  • 10
1

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

John Mitchell
  • 9,653
  • 9
  • 57
  • 91