Java implementation of two computer interactive information method one socket

Source: Internet
Author: User
Tags readline

So-called network programming is the information interaction between two computers, and it is much simpler for programmers to master a programming approach. The Java SDK provides us with some APIs to simplify program writing, and all the classes in network programming exist in java.net.*. You can enter the world of network programming as long as you import it. There are many ways to network programming, and socket is one of them. If you understand the OSI seven-layer network model and the TCP/IP four-layer network model and the network principles and protocols, you will get a deeper understanding between learning network programming.

The basic model of network programming is the client and server, the fixed location provided by the servers, the client can establish the relationship between the two when they know the fixed position and then they can communicate with each other, simply speaking, the communication between the two processes.

First, the relationship between the establishment of computers

Java has a lot of APIs to support network programming, here we mainly explain socket. In fact, Java has quite simplified the network programming mode. You don't have to know much about network protocols and underlying implementations. (Sure, have time to study) Java provides serversocket classes to support.

When you serversocket ServerSocket = new ServerSocket (8888) you have established a fixed location to allow other computers to access you. Here to add a little bit of port support, the port is to uniquely identify each computer only service, the other port number from 0~65535, the first 1024 ports have been TCP/IP as a reserved port, so you can allocate only 1024 ports after. OK, so the server side has been set up. Then we started to set up the client, Java also provided the socket object to support, as long as the client created socket = new Socket (Inetaddress.getlocalhost (), 8888),

The client must know the address of the server, and Java provides a inetaddress.getlocalhost () static method to obtain the server address. Well, the relationship between the two computers has been set up so far.

Second, the transmission of data

Network programming and I/O are always inseparable, Java provides a good flow mechanism to facilitate our byte stream and Unicode reading and writing. Also provides a data buffer oh you read and write.

BufferedReader br=new BufferedReader (New InputStreamReader (Serversocket.getinputstrea ()));

PrintWriter out=new PrintWriter (Serversocket.getoutputstream ());

The two lines above create a stream buffer and convert the raw byte flow to Unicode for operation, while the original stream has the getInputStream () and Getoutputstream () two methods of the socket to get input and output. We can do a simple example by mastering some basic concepts and tools.

1, the establishment of service-side

/**
* @author Licheng
* @date 09-09-05
* @version 1.0
* @function Create service side
* */

Package com.licheng.word.socket;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;

public class MyServer {

/**
* @param args
*/
public static void Main (string[] args) throws ioexception{
ServerSocket serversocket = new ServerSocket (8888); Establish a service-side fixed Address
Socket client = Serversocket.accept (); Listen for and accept connections to this socket
BufferedReader br = new BufferedReader (New InputStreamReader (Client.getinputstream ()));
PrintWriter out = new PrintWriter (Client.getoutputstream ());
while (true) {
String str = br.readline ();
System.out.println (str);
Out.println ("read ...");
Out.flush ();
if ("Stop". Equals (str)) {//Terminate it if the client comes with a stop
Break
}
}
Client.close (); Close socket
}

}

2, establish the client

/**
* @author Licheng
* @date 09-09-05
* @version 1.0
* @function Create Client
* */

Package com.licheng.word.socket;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.net.InetAddress;
Import Java.net.Socket;

public class Client {

private static Socket ServerSocket;

public static void Main (string[] args) throws ioexception{
ServerSocket = new Socket (Inetaddress.getlocalhost (), 8888); Get a link to the server side
BufferedReader in=new BufferedReader (New InputStreamReader (Serversocket.getinputstream ()));
PrintWriter out=new PrintWriter (Serversocket.getoutputstream ());
BufferedReader wt=new BufferedReader (New InputStreamReader (system.in));
while (true) {
String str = wt.readline ();
Out.println (str);
Out.flush ();
if (Str.equals ("Stop")) {
Break
}
System.out.println (In.readline ());
}
Serversocket.close ();
}
}

The client code accepts the client's keyboard input, outputs the information, and then outputs "stop" to do the exit identification.

This program is just a simple communication between two computers. What if multiple customers are accessing a server at the same time? You can try to run a client again, and the result is to throw an exception. How can multiple clients implement it?

Let's simply analyze that the client and the server are like a line. The main channel between the client and server is the socket, and the server uses the accept() method to agree whether to connect the client. So we can solve this problem by using multiple lines, and the program is changed to the following

/**
* @author Licheng
* @date 09-09-05
* @version 1.0
* @function Create service side
* */

Package com.licheng.word.socket;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;

public class MyServer {

/**
* @param args
*/
public static void Main (string[] args) throws IOException {
ServerSocket serversocket = new ServerSocket (8888); Establish a service-side fixed Address
while (true) {
Socket client = Serversocket.accept (); Listen for and accept connections to this socket
BufferedReader br = new BufferedReader (New InputStreamReader (client
. getInputStream ());
PrintWriter out = new PrintWriter (Client.getoutputstream ());
while (true) {
String str = br.readline ();
System.out.println (str);
Out.println ("read ...");
Out.flush ();
if ("Stop". Equals (str)) {//Terminate it if the client comes with a stop
Break
}
}
Client.close (); Close socket
}
}
}

This completes the interaction between multiple users. But the question is again, then the queue execution how to do, it's OK, let's analyze it, that is, when a client and the server complete a communication, the next customer can come in and interact with the server. Can not do at the same time service. So how can we achieve both communication and communication simultaneously? Obviously this is a problem of parallel execution. At this point we should think that threading is the best solution.

To create a thread either directly inherits thread or implements the Runnable interface, and then writes the method inside the main function to run.

/**
* @author Licheng
* @date 09-09-05
* @version 1.0
* @function Create service-side, thread-safe
* */

Package com.licheng.word.socket;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;

public class MyServer extends Thread {

 private Socket Client;
 
 public MyServer (Socket client) {
  this.client = client;
&NBSP}
 
  @Override
 public void Run () {
  try {
    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 ("read ...");
    out.flush ();
    if (str.equals ("Stop")) {
     break;
   &NBSP}
   }
   client.close ();
 &NBSP} catch (IOException e) {
   e.printstacktrace ();
  } finally {
  }
 }

 /**
  * @param args
  */
 public static void Main (string[) args) throws IOException {
  serversocket server=new ServerSocket (8888);
  while (True) {
  myserver mu = new MyServer (server.accept ());
  mu.start ();
  }
 }
}

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.