Java-based socket programming and logging ocket Programming

Source: Internet
Author: User

Java-based socket programming and logging ocket Programming

# Nonsense at the beginning # I have been studying java for half a month. When I used the words in the textbook, I felt that the teaching material was so thick that I had to finish reading it. Suddenly I saw a tutorial on the Internet. The teacher said that I don't need to read the programming language book too carefully. I just want to take a look at it and know what to talk about in it. I don't need to remember it all. Then you can write it all at once, this is the fastest way to compile it. I was wondering, but that was not the case if I had learned C language before. So I accelerated the reading. I quickly browsed some of the methods and classes introduced in the book and brushed them to the Web chapter. I thought socket programming should have a try, do not just look at it as a false handle.

 

This article is original, please note the transfer from http://www.cnblogs.com/liusxg/p/3917624.html

 

Socket programming:

I. What is socket: socket is the communication mechanism of BSD UNIX, which is usually called "socket". Its original English intention is "hole" or "socket ". Some sockets, as the name implies, are like a porous socket, which can provide connection services for multiple ports.

To better understand the socket, you can use the socket to compare the socket.

If the socket is a porous socket, the socket is the place where various electrical appliances are powered. Different electrical appliances require different voltages and currents, but each electrical appliance has its own plug-in port, this is called a "Port ". Electricity used by electrical appliances can be regarded as network resources or various "streams". Electricity is transmitted by wires, so sockets need to connect wires, the wire here is the connection between the server and the client ". The socket initialization process is like the installation process of buying a socket.

On the outlet side, there is a "client", and the power plant that provides power over the wire is a "server ". Both the client and the power plant have an IP address ". There is also a set of transmission and electricity usage rules, such as the number of volts required for power transmission to meet the demand, electrical technical parameters, ports are several holes. This is a "protocol ". Under normal circumstances, we will not render the content of the Protocol, that is, the Protocol is hidden in front of us.

You can have some understanding (the figure is taken from the source code studio ):

      

Ii. Working Principle: For the server, the server first initializes the socket, then binds the port (bind), then listens to the port (listen), calls the accept blocking, and waits for the client to connect to the request. For the client, the client initializes the socket and then applies for a connection ). The client requests a connection. The server accepts the application and replies to the Application for Permission (TCP three-way handshake connection involved here), sends data, and closes the connection. This is an interactive process.

For example, (figure taken from source code studio ):

      

 

 

The Client source code is as follows:

1 import java. io. *; 2 import java.net. *; 3 4 public class Client {5 6 public static void main (String [] args) throws Exception {7 // method stub automatically generated by TODO 8 9 String readline = null; 10 String inTemp = null; 11 // String outTemp = null; 12 String turnLine = "\ n"; 13 final String client = "Client :"; 14 final String server = "Server:"; 15 16 int port = 4000; 17 byte ipAddressTemp [] = {127, 0, 0, 1}; 18 InetAddress IpAddress = InetAddress. getByAddress (ipAddressTemp); 19 20 // first, directly create the socket, Port Number 1 ~ 1023 is saved by the system. Generally, it is located outside 1023, and 21 Socket socket = new Socket (ipAddress, port); 22 23 // creates three streams, the system input stream BufferedReader systemIn, And the socket input stream BufferedReader socketIn, socket output stream PrintWriter socketOut; 24 BufferedReader systemIn = new BufferedReader (new InputStreamReader (System. in); 25 BufferedReader socketIn = new BufferedReader (new InputStreamReader (socket. getInputStream (); 26 PrintWriter socketOut = new PrintWriter (socket. GetOutputStream (); 27 28 while (readline! = "Bye") {29 30 System. out. println (client); 31 readline = systemIn. readLine (); 32 // System. out. println (readline); 33 34 socketOut. println (readline); 35 socketOut. flush (); // refresh to make it received by the Server, or change it to socketOut. println (readline, ture) 36 37 // outTemp = readline; 38 inTemp = socketIn. readLine (); 39 40 // System. out. println (client + outTemp); 41 System. out. println (server + turnLine + inTemp); 42 43} 44 45 systemIn. close (); 46 socketIn. close (); 47 socketOut. close (); 48 socket. close (); 49 50} 51 52}

 

The source code of the Server is as follows:

Import java. io. *; import java.net. *; public class Server {public static void main (String [] args) throws Exception {// method stub automatically generated by TODO String readline = null; String inTemp = null; // String outTemp = null; String turnLine = "\ n"; final String client = "Client:"; final String server = "Server:"; int port = 4000; // byte ipAddressTemp [] = {127, 0, 0, 1}; // InetAddress ipAddress = InetAddress. getByAddress (ipAddressTemp); // first, directly create serversocket ServerSocket serverSocket = new ServerSocket (port );
// Call the server's accept () for blocking (the program will wait here). when a connection request is made, the blocking will be opened and a socket Socket = serverSocket will be returned. accept (); // create three streams: System input stream BufferedReader systemIn, socket input stream BufferedReader socketIn, socket output stream PrintWriter socketOut; BufferedReader systemIn = new BufferedReader (new InputStreamReader (System. in); BufferedReader socketIn = new BufferedReader (new InputStreamReader (socket. getInputStream (); PrintWriter socketOut = new Prin TWriter (socket. getOutputStream (); while (readline! = "Bye") {inTemp = socketIn. readLine (); System. out. println (client + turnLine + inTemp); System. out. println (server); readline = systemIn. readLine (); socketOut. println (readline); socketOut. flush (); // refresh quickly to make the Client receive it, or change it to socketOut. println (readline, ture) // outTemp = readline; // System. out. println (server);} systemIn. close (); socketIn. close (); socketOut. close (); socket. close (); serverSocket. close ();}}

  

The debugging result is as follows:

    

Start the server before debugging. If the client cannot find the server, it cannot run.

The running effect is still very good. Fortunately, you can run it directly after writing it. The key is the correct idea. As a result, I have come up with a rule that no matter what project you want to do, you should first check the materials, understand and understand the principles of the program, and have a clear idea to ensure the success rate of the program. You can also read the java manual to learn about the types of constructors and return values. Provides a java manual download URL http://www.jb51.net/books/128276.html

In addition, through socket programming, I also learned a small debugging skill, that is, debugging multiple monitors by this small triangle.


JAVA socket programming

Run the server class and then the client class.

/**
* Server-side class
*/
Public class Server {
Public static void main (String [] args) throws IOException {
Server server = new Server ();
Server. start ();
}
Public void start () throws IOException {
// Bind ServerSocket to the Service port of the current server
// This port number cannot be bound repeatedly and cannot be executed simultaneously on both sides
ServerSocket ss = new ServerSocket (8888 );
While (true ){

// Accept starts to wait (I/O Block) for the client to connect (start the listener). If there is no client connection, the client waits until it is suspended.
// If a client connection exists, the execution will continue. The returned Socket instance s indicates a connection to the client.
Socket s = ss. accept ();
// Create and start the customer service thread to serve the customer
// The current thread returns to accept again and waits for the next client to connect
New Service (s). start (); // creation thread
}
}
Class Service extends Thread {
Socket s;
Public Service (Socket s ){
This. s = s;
}
Public void run (){
Try {
// S stands for the client
// The in represents the stream passed from the customer.
// The out in s indicates that the stream is transmitted from the server to the client.
InputStream in = s. getInputStream ();
Kernel SC = new kernel (in); // System. in is the operating System Background
OutputStream out = s. getOutputStream ();
// Out. write ("Hello! What do you need? \ N ". getBytes (" GBK "));
// Out. flush (); // clear the buffer to ensure that it is sent to the client.

While (true ){
String str = SC. nextLine (); // IO Block
If (str. equals ("connect to server ")){
Out. write ("connection successful! \ N ". getBytes (" GBK "));
Out. flush ();
Break;
}
}
} Catch (IOException e ){
E. printStackTrace ();
}

}
}
}

/**
* Client class
*/
Public class Client {
Public static void main (String [] args) throws IOException {
... The remaining full text>

Multi-User chat Based on java socket programming

You only implement the ticket chat function, and do not implement the duplex chat function. That is to say, the server does not implement communication between Client A and client B. You will adopt the mv mode. Open a thread in the model function layer and use s. accept () accepts the socket sent from the client and transfers it to another client. If this channel is connected, you can implement duplex communication, which is not very difficult. Please try it carefully.
 

Related Article

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.