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?
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