-2

嗨,我是 C# 的新手,做服务器和客户端以通过 tcp/ip 套接字连接共享文本文件。我使用 BinaryReader / BinaryWriter 从客户端上传到服务器,但从服务器到客户端卡住:从客户端到服务器:

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();

在服务器中:

公共无效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));
   }

}

流.Dispose();

现在我尝试从服务器到客户端使用相同的方式但出现错误

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

stateObject 是错误的?

4

2 回答 2

3

问题:由于套接字在缓冲区中接收数据,可能无法一次读取整个数据。 解决方案:您是否考虑过调用 byteread 时的用途。它handler.EndReceive(ar)会告诉您读取的数据,但意味着您必须检查是否收到了全部数据,如果是,则继续将其转换为字符串。

    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
于 2012-11-14T15:24:33.703 回答
1

记住和Flush写完之后的流。从您迄今为止共享的片段来看,它看起来不像有同花顺。

查看Stream Flush文档

于 2012-08-10T15:01:43.250 回答