This article will complete the remaining part of C # network programming (Protocol formation and File Sending) 4. They were originally a complete article, but because the previous article was too long and too many pages were merged, it may be inconvenient to browse. I split it into two articles. This article is the second half of it. We continue with the previous incomplete step: the client receives files from the server.
4. Implementation of the server that receives file 4.1 from the client
For the server, we only need to implement the sendFile () method left over from the previous chapter. It is commented out in handleProtocol at first. In addition, the operations such as creating a connection and getting a stream are no different from those of receiveFile (), So we propose it as a public method getStreamToClient (). The following is the server code, which only contains the code that has been added and modified. For the original method, I only provide the signature:
Class Server {
Static void Main (string [] args ){
Console. WriteLine ("Server is running ...");
IPAddress ip = IPAddress. Parse ("127.0.0.1 ");
TcpListener listener = new TcpListener (ip, 8500 );
Listener. Start (); // enable listening on control port 8500
Console. WriteLine ("Start Listening ...");
While (true ){
// Obtain a connection and the synchronization method, which is interrupted here
TcpClient client = listener. AcceptTcpClient ();
RemoteClient wapper = new RemoteClient (client );
Wapper. BeginRead ();
}
}
}
Public class RemoteClient {
// Field omitted
Public RemoteClient (TcpClient client ){}
// Start reading
Public void BeginRead (){}
// Call back when the read is complete.
Private void OnReadComplete (IAsyncResult ar ){}
// Process protocol
Private void handleProtocol (object obj ){
String pro = obj as string;
ProtocolHelper helper = new ProtocolHelper (pro );
FileProtocol protocol = helper. GetProtocol ();
If (protocol. Mode = FileRequestMode. Send ){
// The client sends the file, which is the receiving file for the server.
ReceiveFile (protocol );
} Else if (protocol. Mode = FileRequestMode. Receive ){
// The client receives the file, which is the sending file for the server.
SendFile (protocol );
}
}
// Send a file
Private void sendFile (FileProtocol protocol ){
TcpClient localClient;
NetworkStream streamToClient = getStreamToClient (protocol, out localClient );
// Obtain the file path
String filePath = Environment. CurrentDirectory + "/" + protocol. FileName;
// Create a file stream
FileStream fs = new FileStream (filePath, FileMode. Open, FileAccess. Read );
Byte [] fileBuffer = new byte [1024]; // 1 kb each time
Int bytesRead;
Int totalBytes = 0;
// Create a class to get the file sending status
SendStatus status = new SendStatus (filePath );
// Write the file flow to the network flow
Try {
Do {
Thread. Sleep (10); // pause for a better visual effect for 10 ms :-)