嗨,我是c#的新手,并通过tcp / ip socket连接做服务器和客户端共享文本文件。我使用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();
在服务器中:
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();
现在我尝试从服务器到客户端使用相同的方式,但出现错误
var stream = new MemoryStream(state.buffer);
var reader = new BinaryReader(stream);
stateObject是错误吗?
答案 0 :(得分:3)
问题:可能是因为套接字在缓冲区中接收数据,所以无法立即读取整个数据。
解决方案:您是否考虑过调用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
答案 1 :(得分:1)
在编写后记住并Flush
。从目前为止您分享的片段看起来并不像是有同花顺。
查看Stream Flush文档