Home>

This example is just a simple function demonstration.The code is not rigorous,It just shows how the client implements simple code to connect to the server.

The code is tested and compiled under the integrated eclipse tool as shown in the following figure:

Client echoclient.java code:

package com.zhengzz.echo;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.socket;
import java.net.unknownhostexception;
class echoc {
  private socket socket;
  public echoc () {
    //todo auto-generated constructor stub
    try {
      socket=new socket ("localhost", 60000);
    } catch (unknownhostexception e) {
      e.printstacktrace ();
    } catch (ioexception e) {
      e.printstacktrace ();
    }
  }
  public void client () {
    try {
      bufferedreader br=new bufferedreader (new inputstreamreader (socket.getinputstream ()));
      printwriter pw=new printwriter (socket.getoutputstream (), true);
      bufferedreader lbr=new bufferedreader (new inputstreamreader (system.in));
      string linestr=null;
      while ((linestr=lbr.readline ())!=null) {
        pw.println (linestr);
        system.out.println (br.readline ());
        if (linestr.equals ("bye #")) {
          break;
        }
      }
    } catch (ioexception e) {
      e.printstacktrace ();
    }
  }
}
public class echoclient {
  public static void main (string [] args) {
    new echoc (). client ();
  }
}

Server echoserver.java code:

package com.zhengzz.echo;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.printwriter;
import java.net.serversocket;
import java.net.socket;
class echos {
  private serversocket serversocket;
  public echos () {
    try {
      serversocket=new serversocket (60000);
    } catch (ioexception e) {
      e.printstacktrace ();
    }
  }
  public void server () {
    while (true) {
      try {
        socket socket=serversocket.accept ();
        system.out.println ("client:" + socket.getinetaddress () + ":" + socket.getlocalport ());
        bufferedreader br=new bufferedreader (new inputstreamreader (socket.getinputstream ()));
        printwriter pw=new printwriter (socket.getoutputstream (), true);
        string linestr;
        while ((linestr=br.readline ())!=null) {
          system.out.println (linestr);
          pw.println ("--->" + linestr);
        }
      } catch (ioexception e) {
        system.out.println ("Connection disconnected:(");
      }
    }
}
}
public class echoserver {
  public static void main (string [] args) {
    new echos (). server ();
  }
}

The direct debugging results under the eclipse tool are as follows:

Let's look at an example of a helloword level java socket communication.Communication process:

Start the server first, and enter an endless loop to keep listening for connection requests on a certain port.Then run the client, the client sends a connection request,The server sends an acceptance message back to the client after listening to this request.Connection established,Start a thread to handle this request,Then continue to listen to other requests in an endless loop.The client enters the string and presses Enter.Send data to the server.After the server reads the data, it returns the client data.This time the request is processed,The started thread dies.If the client receives data other than "ok",Will send the connection request again and send the data,The server will start another thread to respond for this connection.. . Until the client receives "ok", the client exits.

Server source code:

package com.defonds.socket.begin;
import java.io.bufferedreader;
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.inputstreamreader;
import java.net.serversocket;
import java.net.socket;
public class server {
  public static final int port=12345;//The port number to listen on
  public static void main (string [] args) {
    system.out.println ("The server started.
.. \ n ");
    server server=new server ();
    server.init ();
  }
  public void init () {
    try {
      serversocket serversocket=new serversocket (port);
      while (true) {
        //once blocked, It means that the server and client have obtained a connection
        socket client=serversocket.accept ();
        //handle this connection
        new handlerthread (client);
      }
    } catch (exception e) {
      system.out.println ("Server exception:" + e.getmessage ());
    }
  }
  private class handlerthread implements runnable {
    private socket socket;
    public handlerthread (socket client) {
      socket=client;
      new thread (this) .start ();
    }
    public void run () {
      try {
        //read client data
        datainputstream input=new datainputstream (socket.getinputstream ());
        string clientinputstr=input.readutf ();//It should be noted here that it corresponds to the writing method of the client output stream,Otherwise it will throw eofexception
        //process client data
        system.out.println ("Content sent by the client:" + clientinputstr);
        //Reply to the client
        dataoutputstream out=new dataoutputstream (socket.getoutputstream ());
        system.out.print ("Please enter:\ t");
        //Send a line of keyboard input
        string s=new bufferedreader (new inputstreamreader (system.in)). readline ();
        out.writeutf (s);
        out.close ();
        input.close ();
      } catch (exception e) {
        system.out.println ("Server run exception:" + e.getmessage ());
      } finally {
        if (socket!=null) {
          try {
            socket.close ();
          } catch (exception e) {
            socket=null;
            system.out.println ("The server finally exception:" + e.getmessage ());
          }
        }
      }
    }
  }
}

Client source code:

package com.defonds.socket.begin;
import java.io.bufferedreader;
import java.io.datainputstream;
import java.io.dataoutputstream;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.net.socket;
public class client {
  public static final string ip_addr="localhost";//Server address
  public static final int port=12345;//Server port number
  public static void main (string [] args) {
    system.out.println ("The client starts.
.. ");
    system.out.println ("When the server-side character \" ok \ "is received, the client will terminate \ n");
    while (true) {
      socket socket=null;
      try {
        //Create a stream socket and connect it to the specified port number on the specified host
        socket=new socket (ip_addr, port);
        //Read server-side data
        datainputstream input=new datainputstream (socket.getinputstream ());
        //Send data to the server
        dataoutputstream out=new dataoutputstream (socket.getoutputstream ());
        system.out.print ("Please enter:\ t");
        string str=new bufferedreader (new inputstreamreader (system.in)). readline ();
        out.writeutf (str);
        string ret=input.readutf ();
        system.out.println ("The server side returned:" + ret);
        //Disconnect if "ok" is received
        if ("ok" .equals (ret)) {
          system.out.println ("The client will close the connection");
          thread.sleep (500);
          break;
        }
        out.close ();
        input.close ();
      } catch (exception e) {
        system.out.println ("Client exception:" + e.getmessage ());
      } finally {
        if (socket!=null) {
          try {
            socket.close ();
          } catch (ioexception e) {
            socket=null;
            system.out.println ("Client finally exception:" + e.getmessage ());
          }
        }
      }
    }
  }
}

Note:When the socket output stream write data method is writeutf, the input stream uses readutf to read related data. Otherwise, eofexception will be thrown.

  • Previous Summary of regular expressions in swift
  • Next Examples of XML generation methods commonly used in Android