I have just inherited some code that sends a file from server to client. However, the code only works for text files, and I'm trying to modify it so that it can send and receive zipped files too. But I'm stuck, and don't know how to go about changing it.
The current code looks like this:
- //SERVER
- private void SendFileToClient(SocketPacket state, string PFilename)
- {
- if (File.Exists(PFilename))
- {
- FileStream fileStream = File.Open(PFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
- StreamReader reader = new StreamReader(fileStream);
- byte[] sendBytes = Encoding.ASCII.GetBytes(reader.ReadToEnd());
- MessageBox.Show(sendBytes.Length + "");
- state.m_currentSocket.Send(sendBytes, 0, sendBytes.Length, SocketFlags.None);
- fileStream.Close();
- reader.Close();
- }
- }
- //CLIENT
- public void OnDataReceived(IAsyncResult asyn)
- {
- try
- {
- SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
- int iRx = theSockId.thisSocket.EndReceive(asyn);
- char[] chars = new char[iRx + 1];
- System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
- int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
- System.String szData = new System.String(chars);
- theSockId.message += szData;
- if ((theSockId.message.Length > 0) && ((theSockId.message[0] != '<') ||
- ((theSockId.message[0] == '<') && (theSockId.message.IndexOf("") > -1))))
- {
- DealWithResponse(theSockId);
- }
- else
- WaitForData(theSockId);
- }
- catch (ObjectDisposedException)
- {
- System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
- }
- catch (SocketException se)
- {
- MessageBox.Show(se.Message);
- }
- }
- public void DealWithResponse(SocketPacket theSockId)
- {
- if (theSockId.message != null)
- {
- FileStream fileStream = File.Open(theSockId.theGame.KeyFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
- StreamWriter writer = new StreamWriter(fileStream);
- writer.Write(theSockId.message);
- writer.Close();
- fileStream.Close();
- }
- }
Let me know if you need more of the code. Thank you for taking your time to look at this.
Jan MontanoPosted Jan 28, 2009, 11:46 PM
Buzz me if you're having a problem with it.
SkaPosted Jan 27, 2009, 5:23 AM
Will I still receive it the same way?
Jan MontanoPosted Jan 26, 2009, 9:32 PM
long fileLength = fileStream.Length;
byte[] sendBytes = new byte[fileLength];
SkaPosted Jan 26, 2009, 7:50 PM
Can you please point out how I may be able to use that in the above code?
Sorry for being useless.
Jan MontanoPosted Jan 26, 2009, 6:21 AM