Reproduced Zhang Ziyang Learning Record c # Network Programming 5

Source: Internet
Author: User
Tags getstream sendfile
Document directory
  • 4. The client receives the file
C # network programming (receiving files)-Part.5

This article will be completedPart.4They are a complete article, but because the previous article is long and the number of merged pages is too large, browsing may be inconvenient, 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 :-)
BytesRead = fs. Read (fileBuffer, 0, fileBuffer. Length );
StreamToClient. Write (fileBuffer, 0, bytesRead );
TotalBytes + = bytesRead; // number of bytes sent
Status. PrintStatus (totalBytes); // print the sending status
} While (bytesRead> 0 );
Console. WriteLine ("Total {0} bytes sent, Done! ", TotalBytes );
} Catch {
Console. WriteLine ("Server has lost ...");
}

StreamToClient. Dispose ();
Fs. Dispose ();
LocalClient. Close ();
}

// Receives the file
Private void receiveFile (FileProtocol protocol ){}

// Obtain the stream connected to the remote connection-Public Method
Private NetworkStream getStreamToClient (FileProtocol protocol, out TcpClient localClient ){
// Obtain the location of the remote client
IPEndPoint endpoint = client. Client. RemoteEndPoint as IPEndPoint;
IPAddress ip = endpoint. Address;

// Use the new port number to obtain the remote port used to receive files
Endpoint = new IPEndPoint (ip, protocol. Port );

// Connect to the remote client
Try {
LocalClient = new TcpClient ();
LocalClient. Connect (endpoint );
} Catch {
Console. WriteLine ("unable to connect to the client --> {0}", endpoint );
LocalClient = null;
Return null;
}

// Obtain the stream of the sent file
NetworkStream streamToClient = localClient. GetStream ();
Return streamToClient;
}

// Obtain a random image name
Private string generateFileName (string fileName ){}
}

The sendFile method on the server side is similar to the SendFile () method on the client side. The above code is almost written successfully at a time. In addition, note that I copied the SendStatus class used by the client to the server. Next let's take a look at the client.

4.2 client implementation

Note that the client's SendFile () receives the full file path parameter, but only obtains the file name in the path when writing to the Protocol. This is because the server does not need to know the path of the file on the client, so only the file name is written in the Protocol. To make the SendFile () method of the client more generic, it receives the full path of the local file.

The client's ReceiveFile () implementation is similar to the receiveFile () method on the server. Similarly, to save it locally, I Will generateFileName () on the server to avoid repeated file names () method.

Public class ServerClient: IDisposable {
// Field omitted

Public ServerClient (){}

// Send the message to the server
Public void SendMessage (string msg ){}

// Send file-Asynchronous Method
Public void BeginSendFile (string filePath ){}

Private void SendFile (object obj ){}

// Send file -- Synchronization Method
Public void SendFile (string filePath ){}

// Receives files-Asynchronous Method
Public void BeginReceiveFile (string fileName ){
ParameterizedThreadStart start =
New ParameterizedThreadStart (ReceiveFile );
Start. BeginInvoke (fileName, null, null );
}

Public void ReceiveFile (object obj ){
String fileName = obj as string;
ReceiveFile (fileName );
}

// Receive file -- Synchronization Method
Public void ReceiveFile (string fileName ){

IPAddress ip = IPAddress. Parse ("127.0.0.1 ");
TcpListener listener = new TcpListener (ip, 0 );
Listener. Start ();

// Obtain the port number of the local listener
IPEndPoint endPoint = listener. LocalEndpoint as IPEndPoint;
Int listeningPort = endPoint. Port;

// Obtain the sent protocol string
FileProtocol protocol =
New FileProtocol (FileRequestMode. Receive, listeningPort, fileName );
String pro = protocol. ToString ();

SendMessage (pro); // send the protocol to the server

// Interrupted, waiting for remote connection
TcpClient localClient = listener. AcceptTcpClient ();
Console. WriteLine ("Start sending file ...");
NetworkStream stream = localClient. GetStream ();

// Obtain the path strength for saving the file
String filePath =
Environment. CurrentDirectory + "/" + generateFileName (fileName );

// Create a file stream
FileStream fs = new FileStream (filePath, FileMode. CreateNew, FileAccess. Write );
Byte [] fileBuffer = new byte [1024]; // 1 kb each time
Int bytesRead;
Int totalBytes = 0;

// Read from the cache buffer into the file stream
Do {
BytesRead = stream. Read (buffer, 0, BufferSize );
Fs. Write (buffer, 0, bytesRead );
TotalBytes + = bytesRead;
Console. WriteLine ("processing ing {0} bytes...", totalBytes );
} While (bytesRead> 0 );

Console. WriteLine ("Total {0} bytes received, Done! ", TotalBytes );

Fs. Dispose ();
Stream. Dispose ();
LocalClient. Close ();
Listener. Stop ();
}

// Obtain a random image name
Private string generateFileName (string fileName ){}

Public void Dispose (){
If (streamToServer! = Null)
StreamToServer. Dispose ();
If (client! = Null)
Client. Close ();
}
}

The key sentence above is the "Create protocol" sentence. Note that the mode is changed from Send to Receive, and the name of the file on the server to be received is also passed.

4.3 program testing

Now we have completed all the steps to send and receive files, and we can see that all operations on the server are passive. Next we will modify the Main () Program of the client and create a menu, then, send or receive files based on user input.

Class Program {
Static void Main (string [] args ){

ServerClient client = new ServerClient ();
String input;
String path = Environment. CurrentDirectory + "/";

Do {
Console. WriteLine ("Send File: S1-Client01.jpg, S2-Client02.jpg, S3-Client03.jpg ");
Console. WriteLine ("Receive File: R1-Server01.jpg, R1-Server02.jpg, R3-Server03.jpg ");
Console. WriteLine ("Press 'q' to exit. \ n ");
Console. Write ("Enter your choice :");
Input = Console. ReadLine ();
Switch (input. ToUpper ()){
Case "S1 ":
Client. BeginSendFile (path + "Client01.jpg ");
Break;
Case "S2 ":
Client. BeginSendFile (path + "Client02.jpg ");
Break;
Case "S3 ":
Client. BeginSendFile (path + "Client02.jpg ");
Break;
Case "R1 ":
Client. BeginReceiveFile ("Server01.jpg ");
Break;
Case "R2 ":
Client. BeginReceiveFile ("Server01.jpg ");
Break;
Case "R3 ":
Client. BeginReceiveFile ("Server01.jpg ");
Break;
}
} While (input. ToUpper ()! = "Q ");

Client. Dispose ();
}
}

As this is a console application and asynchronous operations are used, the order of the menu appears a bit messy. It is difficult to describe here. You can download the code and run it as soon as you know :-)

The running result of the program is similar to that in the previous section. I will not map the program here. Next is the last article in this series. It combines the sending string and file transfer functions to create a chat program that can send messages and send and receive files. As for voice chat... when I learn, I will tell you >_<,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.