One 、TCP/IP agreement

Since it's network programming , It involves the interaction between several systems , So the first thing to consider is how to accurately locate one or several hosts on the network , The other is how to transmit data reliably and efficiently . It's going to be used here TCP/IP agreement .

TCP/IP agreement ( Transmission control protocol ) By the network layer IP Protocol and transport layer TCP The agreement consists of .IP Layer is responsible for the location of network hosts , Routing of data transmission , from IP The address can be uniquely determined Internet A host on .TCP Layer is responsible for application-oriented reliable or unreliable data transmission mechanism , This is the main object of network programming .

Two 、TCP And UDP

TCP It's a connection oriented protocol that guarantees reliable transmission . adopt TCP Protocol transfer , What we get is a sequential error free data stream . Two pairs of sender and receiver socket There has to be a connection between , In order to be in TCP Communication based on protocol , When one socket( Is usually server socket) Waiting for a connection to be established , the other one socket You can ask for a connection , Once these two socket Connect , They can do two-way data transmission , Both sides can send or receive .

UDP It's a connectionless protocol , Every datagram is an independent message , Include full source or destination address , It's on the network in any possible path to the destination , So can we get to the destination , The time of arrival at the destination and the correctness of the content cannot be guaranteed .

TCP And UDP difference :

TCP characteristic :

1、TCP It's a connection oriented protocol , Establish a connection with three handshakes , When the communication is completed, the connection should be removed , because TCP It's connection oriented protocol , So it can only be used for point-to-point communication . And establishing a connection also takes time and overhead .

2、TCP There is no size limit on the data to be transmitted , Big data transmission .

3、TCP It's a reliable agreement , It can ensure that the receiver can receive all the data sent by the sender completely and correctly .

UDP characteristic :

1、UDP Is a connectionless communication protocol ,UDP Data includes destination port number and source port number information , No connection required due to communication , So broadcast transmission can be realized .

2、UDP There is a size limit when transferring data , Each transmitted datagram must be limited to 64KB within .

3、UDP It's an unreliable agreement , The datagram sent by the sender does not necessarily arrive at the receiver in the same order .

TCP And UDP application :

1、TCP It has strong vitality in network communication , For example, remote connection (Telnet) And file transfer (FTP) It needs data of variable length to be transmitted reliably . But reliable transmission comes at a price , Checking the correctness of the data content will inevitably take up the processing time of the computer and the bandwidth of the network , therefore TCP The efficiency of transmission is not as good as UDP high .

2,UDP It's easy to operate , And it only requires less supervision , Therefore, it is usually used in the distributed system of LAN with high reliability client/server Applications . For example, video conference system , It doesn't require the audio and video data to be absolutely correct , As long as there's continuity , Obviously in this case UDP It would be more reasonable .

3、 ... and 、Socket What is it?

Socket It's also called " Socket ", Used to describe IP Address and port , Is a handle to a communication chain . Two programs on the network exchange data through a two-way communication connection , One end of this two-way link is called a Socket, One Socket By a IP Address and a port number are uniquely identified . Applications usually go through " Socket " Send a request to the network or answer a network request . Socket yes TCP/IP Protocol is a very popular programming interface , however ,Socket The types of protocols supported are not just TCP/IP A kind of , Therefore, there is no necessary connection between the two . stay Java In the environment ,Socket Programming is mainly based on TCP/IP Network programming of protocol .

Socket Communication process : The server monitors whether a port has a connection request , The client sends the connection request to the server , The server receives the connection request and sends the receiving message to the client , Such a connection is established . Both client and server can send messages to each other to communicate with each other .

Socket The basic working process of is composed of the following four steps :

1、 establish Socket;

2、 Open the connection to Socket I / O stream ;

3、 According to a certain agreement Socket Read and write ;

4、 close Socket.

Four 、Java Medium Socket

stay java.net There are two classes under the package :Socket and ServerSocket.ServerSocket On the server side ,Socket It's used to establish a network connection . When the connection is successful , Both ends of the application produce a Socket example , Operate this instance , Complete the required session . For one Network connection , Sockets are equal , There's no difference , It doesn't have different levels because it's on the server or on the client . Whether it's Socket still ServerSocket Their job is adopt SocketImpl Class and its subclasses .

List several common construction methods :

?
1
2
3
4
5
6
7
8
9
Socket(InetAddress address,int port);// Creates a stream socket and connects it to the specified IP The specified port number of the address
Socket(String host,int port);// Creates a stream socket and connects it to the specified port number on the specified host
Socket(InetAddress address,int port, InetAddress localAddr,int localPort);// Create a socket and connect it to the specified remote port on the specified remote address
Socket(String host,int port, InetAddress localAddr,int localPort);// Create a socket and connect it to the specified remote port on the specified remote host
Socket(SocketImpl impl);// Use user specified SocketImpl Create an unconnected Socket
 
ServerSocket(int port);// Create a server socket bound to a specific port
ServerSocket(int port,int backlog);// Use the specified backlog Create a server socket and bind it to the specified local port number
ServerSocket(int port,int backlog, InetAddress bindAddr);// Use the specified port 、 Listen backlog And the local to bind to IP Address creation server

In the parameters of the construction method ,address、host and port They are the other side of the two-way connection IP Address 、 Host name and client   slogan ,stream To specify socket It's flow socket Or datagram socket,localPort Represents the port number of the local host ,localAddr and bindAddr It's the address of the local machine (ServerSocket The host address of ),impl yes socket Parent class of , It can be used to create serverSocket It can also be used to create Socket.count Indicates the maximum number of connections that the server can support .

Be careful : You have to choose the port number carefully . Each port provides a specific service , Only give the right port , only   Get the right services .0~1023 The port number of is reserved by the system , for example http The port number of the service is 80,telnet The port number of the service is 21,ftp The port number of the service is 23,  So when we choose the port number , It's better to choose one larger than 1023 To prevent conflict .

Several important Socke Method :

?
1
2
3
public InputStream getInputStream();// Method to get the network connection input , At the same time return to a IutputStream Object instances
public OutputStream getOutputStream();// The other end of the method connection will get input , At the same time return to a OutputStream Object instances
public Socket accept();// Used to produce " Blocking ", Until a connection is received , And return a client's Socket Object instances .

" Blocking " It's a term , It makes the program run temporarily " Stop " In this place , Until a conversation happens , Then the program continues ; Usually " Blocking " It's generated by a cycle .

Be careful : among getInputStream and getOutputStream Methods produce a IOException, It has to be captured , Because the stream objects they return , It's usually used by another stream object .

5、 ... and 、 Basic Client/Server Program

Here's a basic client / Server side program code . The main implementation of the server has been listening to a port , Waiting for client connection request . Client according to IP The address and port number are connected to the server , Enter a line of information from the keyboard , Send to server side , And then receive the information from the server , Finally, end the conversation . This program can only accept one client connection at a time .

ps: After this little example is written , The server has been unable to receive messages , It took a long time to debug , Only then discovered the misuse PrintWriter Of print() Method , and BufferedReader Of readLine() Method has never encountered a line break , So I've been waiting to read . I fainted ~~@_@

Client program :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package sock;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
  
public class SocketClient {
     public static void main(String[] args) {
         try {
             /** establish Socket*/
             // Creates a stream socket and connects it to the specified IP The specified port number of the address ( This is our machine )
             Socket socket = new Socket( "127.0.0.1" , 2013 );
             // 60s Overtime
             socket.setSoTimeout( 60000 );
  
             /** Send the information the client is ready to transmit */
             // from Socket Object gets the output stream , And construction PrintWriter object
             PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true );
             // Output the input read string to Server
             BufferedReader sysBuff = new BufferedReader( new InputStreamReader(System.in));
             printWriter.println(sysBuff.readLine());
             // Refresh output stream , send Server Receive the string immediately
             printWriter.flush();
  
             /** It is used to obtain the information transmitted by the server */
             // from Socket Object gets the input stream , And construct the corresponding BufferedReader object
             BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(socket.getInputStream()));
             // Enter to read in a string
             String result = bufferedReader.readLine();
             System.out.println( "Server say : " + result);
  
             /** close Socket*/
             printWriter.close();
             bufferedReader.close();
             socket.close();
         } catch (Exception e) {
             System.out.println( "Exception:" + e);
         }
     }
}

Server side program :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package sock;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
  
public class SocketServer {
     public static void main(String[] args) {
         try {
             /** establish ServerSocket*/
             // Create a ServerSocket In the port 2013 Listen to customer requests
             ServerSocket serverSocket = new ServerSocket( 2013 );
             while ( true ) {
                 // Listen and accept this Socket The connection of , When a request comes, it produces a Socket object , And continue
                 Socket socket = serverSocket.accept();
  
                 /** Get the information from the client */
                 // from Socket Object gets the input stream , And construct the corresponding BufferedReader object
                 BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(socket.getInputStream()));
                 // Get the string read from the client
                 String result = bufferedReader.readLine();
                 System.out.println( "Client say : " + result);
  
                 /** Sending server ready to transmit */
                 // from Socket Object gets the output stream , And construction PrintWriter object
                 PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                 printWriter.print( "hello Client, I am Server!" );
                 printWriter.flush();
  
                 /** close Socket*/
                 printWriter.close();
                 bufferedReader.close();
                 socket.close();
             }
         } catch (Exception e) {
             System.out.println( "Exception:" + e);
         } finally {
//          serverSocket.close();
         }
     }
}

6、 ... and 、 Multi client connection server

The above server-side program can only connect to one client at a time , This is obviously impossible in practical application . The common network environment is that multiple clients connect to a host for communication , So we need to modify the above program .

Design thinking : The server-side main program listens to a certain port , Client initiates connection request , The server-side main program receives the request , At the same time, construct a thread class , Used to take over the session . When one Socket After the conversation , This session will be handed over to the thread for processing , The main program continues to listen .

The following implementation process is : The client establishes a connection with the server , Client sends message , The server processes the message and returns the message , If the client requests to close , The server closes the connection , The communication between the two sides is over .

Client program :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package sock;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
  
public class SocketClient {
     public static void main(String[] args) {
         try {
             Socket socket = new Socket( "127.0.0.1" , 2013 );
             socket.setSoTimeout( 60000 );
  
             PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true );
             BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(socket.getInputStream()));
              
             String result = "" ;
             while (result.indexOf( "bye" ) == - 1 ){
                 BufferedReader sysBuff = new BufferedReader( new InputStreamReader(System.in));
                 printWriter.println(sysBuff.readLine());
                 printWriter.flush();
                  
                 result = bufferedReader.readLine();
                 System.out.println( "Server say : " + result);
             }
  
             printWriter.close();
             bufferedReader.close();
             socket.close();
         } catch (Exception e) {
             System.out.println( "Exception:" + e);
         }
     }
}

Server side program :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package sock;
import java.io.*;
import java.net.*;
  
public class Server extends ServerSocket {
     private static final int SERVER_PORT = 2013 ;
  
     public Server() throws IOException {
         super (SERVER_PORT);
  
         try {
             while ( true ) {
                 Socket socket = accept();
                 new CreateServerThread(socket); // When there is a request , Start a thread processing
             }
         } catch (IOException e) {
         } finally {
             close();
         }
     }
  
     // Thread class
     class CreateServerThread extends Thread {
         private Socket client;
         private BufferedReader bufferedReader;
         private PrintWriter printWriter;
  
         public CreateServerThread(Socket s) throws IOException {
             client = s;
  
             bufferedReader = new BufferedReader( new InputStreamReader(client.getInputStream()));
              
             printWriter = new PrintWriter(client.getOutputStream(), true );
             System.out.println( "Client(" + getName() + ") come in..." );
              
             start();
         }
  
         public void run() {
             try {
                 String line = bufferedReader.readLine();
  
                 while (!line.equals( "bye" )) {
                     printWriter.println( "continue, Client(" + getName() + ")!" );
                     line = bufferedReader.readLine();
                     System.out.println( "Client(" + getName() + ") say: " + line);
                 }
                 printWriter.println( "bye, Client(" + getName() + ")!" );
                  
                 System.out.println( "Client(" + getName() + ") exit!" );
                 printWriter.close();
                 bufferedReader.close();
                 client.close();
             } catch (IOException e) {
             }
         }
     }
  
     public static void main(String[] args) throws IOException {
         new Server();
     }
}

7、 ... and 、 Information sharing

Although the above implementation of a number of client and server connections , But it's still messages that travel between a client and a server . Now we're going to share information , That is, the server can send broadcast messages to multiple clients , The client can also send messages to other clients . It's like a chat room , Information can be shared among multiple clients .

Design thinking : The client loop can send messages to the server without stopping typing , And start a thread , It is specially used to monitor the messages sent by the server and print them out . When the server starts , When to start a monitor The thread that sends the message to the client . Every time a client connection request is accepted , Start a thread for processing , And store the client information in the public collection . When the client sends a message , The server stores the messages in sequence Into the queue , When output is needed , Take out the broadcast from the queue and send it to each client . Client input showuser Command to view the list of online users , Input bye Apply to the server to exit the connection .

PS: The following code in the test found a Chinese garbled small problem , When the file is set UTF-8 When coding , No matter how you set the input stream encoding in your code, it doesn't work , Typing Chinese will still be garbled . Set the file to GBK After the coding , No need to set the input stream code in the code, it can display and transmit Chinese normally .

Client code :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package sock;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
  
public class SocketClient extends Socket{
  
     private static final String SERVER_IP = "127.0.0.1" ;
     private static final int SERVER_PORT = 2013 ;
      
     private Socket client;
     private PrintWriter out;
     private BufferedReader in;
      
     /**
      * Connect to the server , And enter the send message
      */
     public SocketClient() throws Exception{
         super (SERVER_IP, SERVER_PORT);
         client = this ;
         out = new PrintWriter( this .getOutputStream(), true );
         in = new BufferedReader( new InputStreamReader( this .getInputStream()));
         new readLineThread();
          
         while ( true ){
             in = new BufferedReader( new InputStreamReader(System.in));
             String input = in.readLine();
             out.println(input);
         }
     }
      
     /**
      * Used to listen to the server sending messages to the client thread class
      */
     class readLineThread extends Thread{
          
         private BufferedReader buff;
         public readLineThread(){
             try {
                 buff = new BufferedReader( new InputStreamReader(client.getInputStream()));
                 start();
             } catch (Exception e) {
             }
         }
          
         @Override
         public void run() {
             try {
                 while ( true ){
                     String result = buff.readLine();
                     if ( "byeClient" .equals(result)){ // The client applied to quit , The server returns to confirm exit
                         break ;
                     } else { // The output server sends messages
                         System.out.println(result);
                     }
                 }
                 in.close();
                 out.close();
                 client.close();
             } catch (Exception e) {
             }
         }
     }
      
     public static void main(String[] args) {
         try {
             new SocketClient(); // Start client
         } catch (Exception e) {
         }
     }
}

Server-side code :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package sock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
  
  
public class Server extends ServerSocket{
      
     private static final int SERVER_PORT = 2013 ;
      
     private static boolean isPrint = false ; // Whether to output message flag
     private static List user_list = new ArrayList(); // Login user collection
     private static List<ServerThread> thread_list = new ArrayList<ServerThread>(); // The server has thread collection enabled
     private static LinkedList<String> message_list = new LinkedList<String>(); // Storing message queues
      
     /**
      * Create server Socket, Create a thread to send messages to the client , Listen to client requests and process
      */
     public Server() throws IOException{
         super (SERVER_PORT); // establish ServerSocket
         new PrintOutThread(); // Create a thread to send messages to the client
          
         try {
             while ( true ){ // Listen for client requests , Start a thread to process
                 Socket socket = accept();
                 new ServerThread(socket);
             }
         } catch (Exception e) {
         } finally {
             close();
         }
     }
      
     /**
      * Listen for output message request thread class , Send a message to the client
      */
     class PrintOutThread extends Thread{
          
         public PrintOutThread(){
             start();
         }
          
         @Override
         public void run() {
             while ( true ){
                 if (isPrint){ // The messages in the queue are sent to the clients in order , And clear it from the queue .
                     String message = message_list.getFirst();
                     for (ServerThread thread : thread_list) {
                         thread.sendMessage(message);
                     }
                     message_list.removeFirst();
                     isPrint = message_list.size() > 0 ? true : false ;
                 }
             }
         }
     }
      
     /**
      * Server thread class
      */
     class ServerThread extends Thread{
         private Socket client;
         private PrintWriter out;
         private BufferedReader in;
         private String name;
          
         public ServerThread(Socket s) throws IOException{
             client = s;
             out = new PrintWriter(client.getOutputStream(), true );
             in = new BufferedReader( new InputStreamReader(client.getInputStream()));
             in.readLine();
             out.println( " Successfully connected to the chat room , Please enter your name :" );
             start();
         }
          
         @Override
         public void run() {
             try {
                 int flag = 0 ;
                 String line = in.readLine();
                 while (! "bye" .equals(line)){
                     // Check out the list of online users
                     if ( "showuser" .equals(line)) {
                         out.println( this .listOnlineUsers());
                         line = in.readLine();
                     }
                     // First entry , Save the name
                     if (flag++ == 0 ){
                         name = line;
                         user_list.add(name);
                         thread_list.add( this );
                         out.println(name + " Hello , It's time to start chatting ..." );
                         this .pushMessage( "Client<" + name + "> Enter the chat room ..." );
                     } else {
                         this .pushMessage( "Client<" + name + "> say : " + line);
                     }
                     line = in.readLine();
                 }
                 out.println( "byeClient" );
             } catch (Exception e) {
                 e.printStackTrace();
             } finally { // The user exits the chat room
                 try {
                     client.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
                 thread_list.remove( this );
                 user_list.remove(name);
                 pushMessage( "Client<" + name + "> Quit the chat room " );
             }
         }
          
         // Put it at the end of the message queue , Ready to send to client
         private void pushMessage(String msg){
             message_list.addLast(msg);
             isPrint = true ;
         }
          
         // Send a message to the client
         private void sendMessage(String msg){
             out.println(msg);
         }
          
         // Count the list of online users
         private String listOnlineUsers() {
             String s = "--- List of online users ---\015\012" ;
             for ( int i = 0 ; i < user_list.size(); i++) {
                 s += "[" + user_list.get(i) + "]\015\012" ;
             }
             s += "--------------------" ;
             return s;
         }
     }
      
     public static void main(String[] args) throws IOException {
         new Server(); // Start server
     }
}

8、 ... and 、 File transfer

The client transfers files to the server , The server can get the file name to save , Get the file size and calculate the transmission progress , Relatively simple , Post code directly .

Client code :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package sock;
 
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;
  
/**
  * client
  */
public class Client extends Socket{
      
     private static final String SERVER_IP = "127.0.0.1" ;
     private static final int SERVER_PORT = 2013 ;
      
     private Socket client;
     private FileInputStream fis;
     private DataOutputStream dos;
      
     public Client(){
         try {
             try {
                 client = new Socket(SERVER_IP, SERVER_PORT);
                 // Transfer files to the server
                 File file = new File( "c:/test.doc" );
                 fis = new FileInputStream(file);
                 dos = new DataOutputStream(client.getOutputStream());
                  
                 // File name and length
                 dos.writeUTF(file.getName());
                 dos.flush();
                 dos.writeLong(file.length());
                 dos.flush();
                  
                 // Transfer files
                 byte [] sendBytes = new byte [ 1024 ];
                 int length = 0 ;
                 while ((length = fis.read(sendBytes, 0 , sendBytes.length)) > 0 ){
                     dos.write(sendBytes, 0 , length);
                     dos.flush();
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 if (fis != null )
                     fis.close();
                 if (dos != null )
                     dos.close();
                 client.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
      
     public static void main(String[] args) throws Exception {
         new Client();
     }
}

Server-side code :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package sock;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
  
/**
  * The server
  */
public class Server extends ServerSocket{
  
     private static final int PORT = 2013 ;
      
     private ServerSocket server;
     private Socket client;
     private DataInputStream dis;
     private FileOutputStream fos;
      
     public Server() throws Exception{
         try {
             try {
                 server = new ServerSocket(PORT);
                  
                 while ( true ){
                     client = server.accept();
                      
                     dis = new DataInputStream(client.getInputStream());
                     // File name and length
                     String fileName = dis.readUTF();
                     long fileLength = dis.readLong();
                     fos = new FileOutputStream( new File( "d:/" + fileName));
                      
                     byte [] sendBytes = new byte [ 1024 ];
                     int transLen = 0 ;
                     System.out.println( "---- Start receiving files <" + fileName + ">, File size is <" + fileLength + ">----" );
                     while ( true ){
                         int read = 0 ;
                         read = dis.read(sendBytes);
                         if (read == - 1 )
                             break ;
                         transLen += read;
                         System.out.println( " Receiving file progress " + 100 * transLen/fileLength + "%..." );
                         fos.write(sendBytes, 0 , read);
                         fos.flush();
                     }
                     System.out.println( "---- Receive the file <" + fileName + "> success -------" );
                     client.close();
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             } finally {
                 if (dis != null )
                     dis.close();
                 if (fos != null )
                     fos.close();
                 server.close();
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
      
     public static void main(String[] args) throws Exception {
         new Server();
     }
}

Network programming TCP/IP Achieve client and client chat more related articles

  1. Socket Network programming (TCP/IP/ port / class ) And examples

    Socket Network programming (TCP/IP/ port / class ) And examples original text :C# Socket The essence of web programming from : A little cold rain We are explaining Socket Before programming , Let's look at a few and Socket Concepts that are closely related to programming : TCP/IP level ...

  2. Network programming TCP/IP Detailed explanation

    Network programming TCP/IP Detailed explanation 1. Network communication Repeater : signal amplifier A hub (hub): It's a form of repeater , The difference is that hubs can provide multi port services , Multi port repeater , Every packet is sent in the form of broadcast , It's easy to block the network . ...

  3. JAVA Basic knowledge of network programming ——-TCP/IP agreement ,socket signal communication , Server client communication demo

    OSI Model layering OSI The model refers to the international organization for standardization (ISO) The open systems interconnection reference model is proposed (Open System Interconnection Reference Model,OSI/RM), It divides the network into seven ...

  4. python Network programming TCP/IP socket UDP

    TCP/IP brief introduction Although we are very familiar with the Internet now , But the emergence of the computer network is much earlier than the Internet . Computers for networking , It's necessary to stipulate the communication protocol , Early computer networks , It's up to each manufacturer to define a set of agreements ,IBM.Apple and Micro ...

  5. Python Medium socket Network programming (TCP/IP,UDP) Explain

    Socket is a basic component in network programming (socket). A socket is basically between two endpoint programs " Information channels ". Programs may be distributed on different computers , Sending messages to each other through sockets . The socket consists of two : Server set ...

  6. 18 Network programming -TCP/IP Introduction of each layer (5 Layer model )

    1.TCP/IP Five layer protocol The physical layer -- Data link layer -- The network layer -- Transport layer -- application layer We will apply the layer , The presentation layer , Session layer and application layer , from tcp/ip From the perspective of five layer protocol, the origin and function of each layer are explained , Make clear the main agreement of each layer Just ...

  7. Network programming -TCP/IP Introduction of each layer (5 Layer model )

    1.TCP/IP Five layer protocol The physical layer -- Data link layer -- The network layer -- Transport layer -- application layer We will apply the layer , The presentation layer , Session layer and application layer , from tcp/ip From the perspective of five layer protocol, the origin and function of each layer are explained , Make clear the main agreement of each layer Just ...

  8. Fifty-three Network programming TCP/IP brief introduction

    Although we are very familiar with the Internet now , But the emergence of the computer network is much earlier than the Internet . Computers for networking , It's necessary to stipulate the communication protocol , Early computer networks , It's up to each manufacturer to define a set of agreements ,IBM.Apple and Microsoft They all have their own ...

  9. UNIX Network programming ——TCP/IP brief introduction

    One .ISO/OSI Reference model OSI(open system interconnection) The open systems interconnection model is made up of ISO(International Organization for Standardi ...

Random recommendation

  1. mako Template debugging and use skills

    django The default template is too inflexible , I want to put a number 0.15 Display as 15% It takes a lot of effort , It's not good !!! I looked up several template systems on the Internet , Yes Jinja2 wait , Finally found mako Be able to directly support python The sentence of , Most flexible , Decisive election ...

  2. Based on density clustering DBSCAN and kmeans Algorithm comparison

    According to the characteristics of each industry , Many clustering algorithms have been proposed , It can be simply divided into : Based on hierarchy . Divide . density . graph theory . There are several categories of grids and models . among , A density based clustering algorithm is proposed DBSCAN The most representative .   scene One Suppose there is a set of data as shown in the figure below , Generate the data ...

  3. android sdcard information acquisition

    There are two kinds of mobile storage , One is The storage that comes with the phone , be called internal storage, Another kind of storage that users insert extra , be called removable storage ( It's external sdcard Part of ). removabl ...

  4. Apache Kafka Getting started with development (2)

    Apache Kafka The goal is to unify offline and online processing , And Flume and Scribe Comparison ,Kafka It has more advantages in processing activity flow data . But from the perspective of Architecture ,Kafka With the traditional messaging system ( for example ActiveMQ or Ra ...

  5. php About the calculation method of latitude and longitude distance The successful version

    1.PHP Realize the calculation of distance through longitude and latitude The unit is kilometers function getdistance($lng1,$lat1,$lng2,$lat2)// Calculate the distance according to latitude and longitude { // Turn angle to foxiness   $radLat ...

  6. Java Foundation Series --09_ aggregate 2

    I introduced the main architecture of the collection yesterday , Today's main goal is to learn about iterator traversal and List Unique functions of . iterator :      summary : Because of the different data structures of various sets , So storage is different , It's taken out in a different way . But they all have judgment and gain ...

  7. Use JSR-303 check

    package com.ieou.comac.module.web.dto.employee; import lombok.Data; import javax.validation.constrai ...

  8. redist The command operation ( Two )-- Hash Hash, list List

    1.Redis Hash (Hash) Refer to the rookie tutorial :http://www.runoob.com/redis/redis-hashes.html Redis hash It's a string Type of field and v ...

  9. react The first day

    1. Download the source code :github 16.7 edition 2. Find the notes :https://react.jokcy.me/book/api/react.html#

  10. maven project ( turn )

    I remember understanding maven I've seen it repeated several times before maven Teaching video of . I don't know if I'm too savvy or how to drop it , I just can't figure it out , Now it's clear , Basically getting started . Write this blog post , It's just to help people who are just as interested in maven People in a daze . ...