In fact, the simple understanding of network programming is that two computers communicate data to each other, for programmers, to master a programming interface and use a programming model is relatively simple, the Java SDK provides some relatively simple API to do this work. Socket is one of them, for Java, these APIs exist with java.net this package, so as long as the import of this package can prepare network programming.
The basic model of network programming is the client-to-server model, which simply means that two processes communicate with each other, and one must provide a fixed location, while the other only needs to know the fixed location. and to establish the connection between the two, and then complete the communication of the data can be, here provide a fixed location is often called the server, and the establishment of a connection is usually called the client, based on this simple model, you can enter the network programming.
Java's support for this model has a number of APIs, and here I just want to introduce a programming interface for sockets, which simplifies the programming interface of the socket for Java. First, let's talk about how the service that provides the fixed location is built. Java provides serversocket to support it. In fact, when you create a power object of the class and provide a port resource you build a fixed location that allows other computers to access you, ServerSocket server=new serversocket (6789); It is important to note that the allocation of the port must be unique. Because the port is to uniquely identify each computer's unique service, and the other port number is from 0~65535, the first 1024 ports have been TCP/IP as the reserved port, so you can only allocate a port of 1024 after. Well, we have a fixed position. What is needed now is a connecting wire. The connection line is first requested by the client. So Java also provides a socket object to support it, as long as the client creates a socket instance object to support it. Socket Client
=new Socket (Inetaddress.getlocalhost (), 5678); The client must know the IP address of the server, and for a bit Java also provides a related class inetaddress An instance of the object must be provided by its static method, and its static method mainly provides a way to get the native IP and get inetaddress directly by name or IP.
The above method can basically establish a line to allow two computers to communicate with each other, but how is the data transmitted? In fact I/O operations are always tied to network programming. Because the underlying network is the continuation of the data, unless the remote call, the core of the processing problem is executed, otherwise the data interaction depends on the IO operation, So you also have to import java.io this package. Java's IO operation is also not complex, it provides readers and writer for Byte stream and Unicode, and then provides a buffer for reading and writing data.
BufferedReader in=new BufferedReader (New InputStreamReader (Server.getinputstream ()));
PrintWriter out=new PrintWriter (Server.getoutputstream ());
The above two sentences is to establish a buffer and the original byte flow into Unicode can be manipulated, and the original stream of bytes from the socket two methods, getInputStream () and Getoutputstream () side, respectively, to get input and output, So now that we have the basic model and the basic operating tools, we can do a simple socket routine.
Service party:
Import java.io.*;
Import java.net.*;
public class MyServer{
public static void Main (string[] args) throws IOException{
ServerSocket server=new ServerSocket (5678);
Socket client=server.accept ();
BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
PrintWriter out=new PrintWriter (Client.getoutputstream ());
while (true){
String Str=in.readline ();
System.out.println (str);
OUT.PRINTLN ("has receive.");
Out.flush ();
if (Str.equals ("End"))
Break
}
Client.close ();
}
}
The main purpose of this program is that the server continuously receives the information written by the client only, the client sends an "END" string to exit the program, and the server will also make "receive" in response to inform the client that the message has been received.
Client code:
Import java.net.*;
Import java.io.*;
public class Client{
static Socket server;
public static void Main (string[] args) throws Exception{
Server=new Socket (Inetaddress.getlocalhost (), 5678);
BufferedReader in=new BufferedReader (New InputStreamReader (Server.getinputstream ()));
PrintWriter out=new PrintWriter (Server.getoutputstream ());
BufferedReader wt=new BufferedReader (New InputStreamReader (system.in));
while (true){
String Str=wt.readline ();
Out.println (str);
Out.flush ();
if (Str.equals ("End")){
Break
}
System.out.println (In.readline ());
}
Server.close ();
}
}
The client code accepts the client's keyboard input, outputs the information, and then outputs "End" to do the exit identification.
This program is just a simple communication between two computers, if multiple clients access a server at the same time? You can try to run a client again, and the result is an exception. So how do multiple clients implement it?
In fact, a simple analysis, you can see that the main channel of customer and service communication is the socket itself, and the server through the Accept method is to agree to establish communications with customers. This is when the customer establishes the socket. The server will also use this link to communicate successively, so as long as we have more than one connection. Then our program can be changed to the following:
Server:
Import java.io.*;
Import java.net.*;
public class MyServer{
public static void Main (string[] args) throws IOException{
ServerSocket server=new ServerSocket (5678);
while (true){
Socket client=server.accept ();
BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
PrintWriter out=new PrintWriter (Client.getoutputstream ());
while (true){
String Str=in.readline ();
System.out.println (str);
OUT.PRINTLN ("has receive.");
Out.flush ();
if (Str.equals ("End"))
Break
}
Client.close ();
}
}
}
This only adds an outer while loop, and the purpose of this loop is to assign a socket to the client when a client comes in, and this is where the customer's "End" message is received. Now the interaction between multiple customers is realized. But then again, the problem is that it solves a multi-client, but it is queued for execution. In other words, when a customer and the server to complete a communication after the next customer can come in and server interaction, unable to do at the same time service, then how to achieve at the same time can communicate with each other and can communicate at the same time? Obviously this is a parallel execution problem. So threading is the best solution.
So the following question is how to use threads. The first thing to do is to create a thread and make it available to connect to the network. The thread then performs the operation just now, to create a thread that either directly inherits the thread or implements the Runnable interface. To establish a connection to the socket, just pass the reference. and to execute a thread you have to rewrite the run method, and what the Run method does is what the single-threaded version of main does, so our program becomes this:
Import java.net.*;
Import java.io.*;
public class multiuser extends Thread{
Private Socket client;
Public multiuser (Socket c){
This.client=c;
}
public void Run (){
Try{
BufferedReader in=new BufferedReader (New InputStreamReader (Client.getinputstream ()));
PrintWriter out=new PrintWriter (Client.getoutputstream ());
Mutil User but can ' t parallel
while (true){
String Str=in.readline ();
System.out.println (str);
OUT.PRINTLN ("has receive.");
Out.flush ();
if (Str.equals ("End"))
Break
}
Client.close ();
}catch (IOException ex){
}finally{
}
}
public static void Main (string[] args) throws IOException{
ServerSocket server=new ServerSocket (5678);
while (true){
Transfer location Change single user or Multi user
Multiuser mu=new multiuser (server.accept ());
Mu.start ();
}
}
}
My class inherits directly from the thread class. And the constructor passes the reference and establishes a connection to the client socket so that each thread has one. A communication pipeline. Similarly, we can fill out the Run method and hand over the previous operation to the thread, so that the multi-client parallel socket is built up.
This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/JaunLee/archive/2007/09/29/1805760.aspx
Classic example of Java socket network programming (GO)