Java Socket network programming beginner

Source: Internet
Author: User

From: http://www.wang48.com/jishubaodianview? Jsd_id = 4902

(Go to your blog, and go to the Province)

 

In fact, a simple understanding of network programming is that two computers communicate data with each other. For programmers, it is much easier to master a programming interface and use a programming model, java SDK provides some relatively simple APIs to complete these tasks. Socket is one of them. For Java, these APIS exist in the java.net package, so you only need to import this package to prepare network programming.
The basic model of network programming is the client-to-server model. Simply put, two processes communicate with each other, and one of them must provide a fixed location, the other one only needs to know the fixed position. And establish the relationship between the two, and then complete the data communication. Here, a fixed location is usually called a server, and a connection is usually called a client. Based on this simple model, you can access network programming.
JAVA supports many APIs for this model. Here I only want to introduce socket programming interfaces. For Java, the socket programming interfaces have been simplified. First, let's discuss how a service provider that provides a fixed location is built. Java provides serversocket for its support. in fact, when you create a powerful object of this class and provide a port resource, you will create a fixed location for other computers to access you, serversocket Server = new serversocket (6789 ); note that the port allocation must be unique. Because the port is used to uniquely identify the unique service of each computer, and the port number ranges from 0 ~ The first 65535 ports have been reserved by TCP/IP. Therefore, you can only allocate 1024 ports later than 1024. Now we have a fixed position. All we need is a connection line. The connection line is requested by the customer first. Therefore, Java also provides a socket object to support it, as long as the customer creates a socket Instance Object for support. Socket Client
= New socket (inetaddress. getlocalhost (), 5678); the client must know the IP address of the server. For Java, a related class of inetaddress must be provided for the instance of this object through its static method, its static method mainly provides the method of obtaining the local IP address and directly obtaining the inetaddress through the name or IP address.
The above method can basically establish a line for the two computers to communicate with each other, but how is data transmitted? In fact, I/O operations are always closely related to network programming. Because the underlying network continues data, unless it is called remotely, the core of the problem is execution. Otherwise, data interaction still depends on Io operations, so you must also import Java. io package. java Io operations are not complex. It provides readers and writers for byte streams 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 statements are used to establish a buffer and convert the original byte stream to Unicode. The original byte stream comes from the two methods of socket, getinputstream () and getoutputstream, to get the input and output respectively, now we have the basic model and basic operation tools, we can make a simple socket routine.
Service provider:
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 keeps receiving the information written by the client, and the client will exit the program after sending the "end" string, and the server will also respond to "receive, 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 {
Servers = 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 is to accept the customer's keyboard input, output the information, and then output "end" for exit identification.
This program is just a simple communication between two computers. What if multiple customers access one server at the same time? You can try to run another client and the result will throw an exception. How can we implement multiple clients?
In fact, after a simple analysis, we can see that the main channel for communication between the customer and the service is the socket itself, and the server agrees to establish communication with the customer through the accept method. in this way, when the customer establishes a socket. The server will also use this connection to communicate successively, so as long as we have multiple connections. 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 ();
}
}
}
Here, only an outer while loop is added. The purpose of this loop is to assign a socket to a customer when the customer comes in until the customer completes an interaction with the server, here, the customer's "end" message is received. now, the interaction between multiple customers is realized. However, the problem arises again. Although this solution solves multiple customers, it is executed in queue. That is to say, when a customer communicates with the server once, the next customer can come in and interact with the server, and cannot provide services at the same time, so how can we achieve both communication and communication at the same time? Obviously, this is a problem of parallel execution. So thread is the best solution.
The following question is how to use a thread. The first thing to do is to create a thread and connect it to the network. Then, the thread will execute the previous operation. To create a thread, either directly inherit the thread or implement the runnable interface. to establish a connection with the socket, you only need to pass the reference. to execute the thread, you must override the run method, and the run method does what the single-thread version main did. Therefore, our program becomes like 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 is inherited directly from the Thread class, and the reference is passed through the constructor to establish a connection with the client socket, so that each thread has. A communication pipeline. Similarly, we can enter the run method and hand over the previous operations to the thread to complete, so that multiple clients can establish parallel sockets.

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.