嗨,我是 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 是错误的?