Recently in writing this computer network, and then asked us to write a server, a start confused! But then a look at the data figured out, haha ~ and then he snapped out. All right, gossip, just look at the code!
Client.java
Package Exercise01;import Java.io.*;import java.net.*;p ublic class Client {private String hostname; private int port; Socket socket = NULL; Public Client (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 static void Main (string[] argv) {//create A object for the current class client client = new Client ("localhost", 8181); try{ Trying to establish a connection to the server Client.connect (); 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 ()); } } }
Server.java
Package Exercise01;import Java.net.*;import java.io.*;p ublic class Server {private ServerSocket serversocket;private int port;public Server (int port) {this.port = port;} public void StartServer () throws Ioexception{system.out.println ("Starting the socket server at the port:" + port); ServerS Ocket = new ServerSocket (port);//listen the clients. Block until one connectsSystem.out.println ("Waiting for Clients ..."); Socket client = Serversocket.accept ();//a client has connected and send the Welcome messagesendmessage (client);} Send the display messageprivate void SendMessage (Socket client) throws IOException {BufferedWriter writer = new Buffered Writer (New OutputStreamWriter (Client.getoutputstream ())); Writer.write ("Hello. You is connected to a simple Socket Server. "); Writer.flush (); Writer.close ();} /** * Create A server object and start the server * * @param argv */public static void Main (string[] argv) {int port = 818 1;//start the Servertry{server server = new server (port); Server.startserver ();} catch (IOException IoE) {ioe.printstacktrace ();}}}
Change the package name and you can run.
Java Network programming Single thread Client-server