Multi-client and server-side communication using multithreading 1

Source: Internet
Author: User

Server.java

Package socket;

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

/**
* Chat room service side
* @author Xiaoming
*
*/
public class Server {
/**
* The ServerSocket running on the service side has two main functions:
* 1: Request a service port from the system, the client is connected to the server through this port.
* 2: Listen to the service port, once the client has established a connection with the server, it will
* Automatically create a socket and pass the socket to the connected
* The client interacts.
*
*/
Private ServerSocket server;

Public Server ()
{
try{
/**
* When instantiating a serversocket, specify the service port to which the system is requested. Note that the port
* Cannot be consistent with the port number requested by other applications in the current system.
* Otherwise, the port will be thrown out of the exception.
*/
SYSTEM.OUT.PRINTLN ("Starting service side ...");
Server = new ServerSocket (8088);
SYSTEM.OUT.PRINTLN ("Service side start up!") ");
}catch (Exception e) {

}
}

public void Start ()
{
try {
while (true)
{
System.out.println ("Waiting for Client Connection");
Socket socket = server.accept ();
Accept is used to sense the socket.
SYSTEM.OUT.PRINTLN ("A client is connected in. ");

ClientHandler hander = new ClientHandler (socket);
thread T1 = new thread (hander);
T1.start ();
}
/**
* Ready to accept client connections
*
* This is a blocking method.
* Once the Accpet () method is called, the server is blocked here, waiting for the client to connect.
* When we start the client, the client instantiates the socket and finds the application via IP.
* then Accpet () will react immediately. The Accpet () method returns a socket when it finishes executing.
* This socket allows you to communicate with the client that has just established the connection.
* Client creates a socket and the server receives a socket via accept ().
* This is the time to communicate.
* Exceptions need to be handled.
*/
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

public static void Main (string[] args) {
Server server = new server ();
Server.start ();
}

/**
* When reading the information sent by the remote computer through the input stream
* The Br.readline () method reacts differently to client disconnects on different systems
* When Windows client disconnects, it throws an exception directly
* The Linux client will return NULL when it disconnects
* The thread task is responsible for interacting with the specified client
* @author Xiaoming
*
*/
Private class ClientHandler implements runnable{
private socket socket;
Private String host;
The socket needs to be passed in when it is created to interact with the client
Public ClientHandler (socket socket) {
This.socket = socket;
Get remote address information through the socket
InetAddress address = socket.getinetaddress ();
Host = Address.gethostaddress ();
}
@Override
public void Run () {
try{
System.out.println ("Enters the thread, is now calling the run () method");
InputStream in = Socket.getinputstream ();
InputStreamReader ISR = new InputStreamReader (in);
BufferedReader br = new BufferedReader (ISR);
String message = NULL;
SYSTEM.OUT.PRINTLN ("Client address is:" + host);
System.out.println ("Try output br.readline ()" + br.readline ());
System.out.println ("While the topmost statement");

while ((message = Br.readline ()) = null)
{
SYSTEM.OUT.PRINTLN ("read Data");
SYSTEM.OUT.PRINTLN (host + "say" + message);
SYSTEM.OUT.PRINTLN ("A client Connected");
}
if (message = = NULL) {
SYSTEM.OUT.PRINTLN ("message is empty");
}
Br.close ();
}catch (IOException e) {
E.printstacktrace ();
}finally{
Br.close ();
}
}

}

}

Client.java

Package socket;

Import Java.io.BufferedWriter;
Import java.io.IOException;
Import Java.io.OutputStreamWriter;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import Java.util.Scanner;

/**
* Chat Room Client
* @author Xiaoming
*
*/
public class Client {
/**
* Socket
* Encapsulates the communication details of the TCP protocol so that we can simply use it to complete the TCP communication
* Two streams are provided after the socket connection to complete the data connection to the remote computer via read and write operations of two streams
* Complete the data exchange with the remote computer.
*/
private socket socket;
public Scanner Reader;
/**
* Used to initialize the client
*/
Public Client ()
{
try {
/**
* You need to pass in two parameters when instantiating a socket:
* 1: IP address on server
* 2: Port number on the server
* The computer where the server is located can be found by IP address
* The port can be used to locate the computer running on the server.
* Server-side applications
* Note that the process of instantiating a socket is the process of connecting, if
* Connection failure will throw an exception.
*/
reader = new Scanner (system.in);

SYSTEM.OUT.PRINTLN ("Connecting to Server ...");
Socket = new Socket ("localhost", 8088);
SYSTEM.OUT.PRINTLN ("Establish a connection with the server! ");

/**
* There are two parameters, one is IP address, the other is the port number
*/
/**
* All applications need to request a network port with the operating system when using the network
*
*/
/**
* Exception to our own handling, do not throw
*/
}catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

}

/**
* Do not rely too much on the main method when writing programs
* How the client starts working
*/
public void Start ()
{
try{
Socket.getoutputstream ();
Piling
You can find where the code is wrong.
PrintWriter pw = new PrintWriter (
New BufferedWriter (
New OutputStreamWriter (
Socket.getoutputstream ())), true);
Pw.write ("Hello service side");
Using the above statement is wrong, use a method with automatic row refresh
Stop subconsciously writing that statement.
for (int i = 0; i < i++) {
PW.PRINTLN ("Hello Service side!") "+ i);
//}
while (true)
{
String line = Reader.nextline ();
Pw.println (line);
}

}catch (Exception e) {
E.printstacktrace ();
}
}
public static void Main (string[] args) {
Client client = new Client ();
Client.start ();
}

}

Multi-client and server-side communication using multithreading 1

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.