Java Network Programming Multi-Threading Client-server

Source: Internet
Author: User

In front of the nonsense, now directly read the code it!

Threadedclient.java

Package Exercise01;import Java.io.*;import java.net.*;p ublic class Threadedclient {private String hostname;    private int port;        Socket socket = NULL;    Public threadedclient (String hostname, int port) {//constructor of the Client class This.hostname = hostname;    This.port = port; } public void Connect () throws Unknownhostexception, ioexception{System.out.println ("Attempting connect to" + H    Ostname + ":" +port);    Socket = new socket (hostname,port);    System.out.println ("Connection established!");    } public void Readresponse () throws ioexception{String Userinput;    BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));    System.out.println ("Response from the server:");    while ((Userinput = Reader.readline ()) = null) {System.out.println (userinput); }} public void Askfortime () throws ioexception{bufferedwriter writer = new BufferedWriter (New OUTPUTSTREAMW Riter (socket.getoutputstreAM ()));    Writer.write ("Time?");    Writer.newline ();    Writer.flush (); } public static void Main (string[] argv) {//create A object for the current class Client threadedclient Clie    NT = new Threadedclient ("localhost", 8181);        try{//trying to establish a connection to the server Client.connect ();        Ask the server for Time Client.askfortime ();        If connection succeed, return the input contents client.readresponse (); }catch (unknownhostexception ukhe) {//if the host not found System.err.println ("host unknown! Connection can not be established! ");} catch (IOException IoE) {//if the server doesn ' t work System.err.println ("Connection can not is established! The server may is not on! Check the error message!    "+ioe.getmessage ()); }    }        }
Threadedserver.java

Package Exercise01;import Java.io.*;import Java.net.*;import Java.util.date;public class Threadedserver {private ServerSocket serversocket;private int port;public threadedserver (int port) {this.port = port;} Get the thread startedpublic void Start () throws Ioexception{system.out.println ("Starting the server at the port:" + por t); serversocket = new ServerSocket (port);//instantial an object Clientsocket client = Null;//set The condition to be true For endless Loopswhile (true) {System.out.println ("Waiting for Clients ..."); client = Serversocket.accept (); System.out.println ("The following client has connected:" + client.getinetaddress (). Getcanonicalhostname ());//A Client have connected to the serverthread thread = new Thread (new Socketclienthandler (client)); Thread.Start ();}} /** * Instantial An object of Class Threadedserver and start the server * * @param argv */public static void Main (string[ ] argv) {//set The default port numberint port = 8181;try{//initializing the socket serverthreadedserVer threadedserver = new Threadedserver (port); Threadedserver.start ();} catch (IOException IoE) {ioe.printstacktrace ();}}} Class Socketclienthandler implements Runnable{private socket Client;public Socketclienthandler (socket client) { this.client = client;} /** * Get the thread started by the Run method */@Overridepublic void Run () {try{system.out.println ("thread started with n Ame: "+ thread.currentthread (). GetName ()); Readresponse ();} catch (IOException IoE) {ioe.printstacktrace ();} catch (Interruptedexception IE) {ie.printstacktrace ();}}  /** * Read the response from the server * @throws IOException * @throws interruptedexception */private void Readresponse () Throws IOException, interruptedexception {String userinput; BufferedReader reader = new BufferedReader (New InputStreamReader (Client.getinputstream ())); while (Userinput = Reader.readline ()) = null) {if (Userinput.equals ("Time?")) {System.out.println ("Request to send time! Sending time current. "); Sendtime (); break;}}} /** * Send the current time to thE Server * @throws IOException * @throws interruptedexception */private void Sendtime () throws IOException, Interruptedexc eption {bufferedwriter writer = new BufferedWriter (New OutputStreamWriter (Client.getoutputstream ())); Writer.write ( New Date (). toString ()); Writer.flush (); Writer.close ();}}


Did it bring you a little inspiration?


Java Network Programming Multi-Threading Client-server

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.