Socket and runnable for multi-person access servers

Source: Internet
Author: User

/*
* Socket and runnable implement multi-person access server
* Because each connection starts a new thread, multiple customers can connect to the server at the same time.
* Basic operating procedures are as follows:
* 1) programming and running server programs
* 2) Open multiple Telnet windows
* 3) Switch between these windows and type the command. Note that you can communicate through these windows at the same time.
* 4) When this is done, switch to the program window where you started the server and use CTRL + C to forcibly close it
* */
Package threaded;


Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import Java.util.Scanner;


public class Threadedechoserver {


public static void Main (string[] args) {
TODO auto-generated Method Stub
try{
int i = 1;
ServerSocket s = new ServerSocket (8189);
while (true) {
Socket incoming = S.accept ();
System.out.println ("spawning" + i);
Runnable r = new Threadedechohandler (incoming);
Thread t = new Thread (r);
i++;
}
}catch (IOException e) {
E.printstacktrace ();
}

}


}


Class Threadedechohandler implements runnable{
Private Socket incoming;
Public Threadedechohandler (Socket i) {
incoming = i;
}

public void Run () {
try{
try{
InputStream instream = Incoming.getinputstream ();
OutputStream OutStream = Incoming.getoutputstream ();
Scanner in = new Scanner (instream);
PrintWriter out = new PrintWriter (OutStream, true);
Out.println ("Hello Enter BYE to exit");
Boolean done = false;
while (!done && in.hasnextline ()) {
String line = In.nextline ();
Out.println ("Echo:" + line);
if (Line.trim (). Equals ("BYE")) {
Done = true;
}
}
}finally{
Incoming.close ();
}
}catch (IOException e) {
E.printstacktrace ();
}
}
}

Sockets and runnable implement multi-person access servers

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.