Java socket programming to achieve a simple greeting service _java

Source: Internet
Author: User
Tags int size readline socket

This article illustrates the Java socket programming to achieve a simple greeting service detailed code for your reference, the specific contents are as follows

Server side:

Implement one of the simplest Hello services, print out the client IP address to the console, send a string of characters (Hello, Java Socket) to any connected client, and then close the connection to the client. Wait for the next client connection request to arrive.

Client:

Implement one of the simplest socket connections to the Hello server side, receive the byte data sent over the server side to print and output the content to the console.

Key Tips:

Because Java provides a lot of input and output flow APIs, causing many beginners to contact Java socket programming, due to the lack of understanding of the nature of the network byte communication, directly a readline () to accept the socket byte stream. This is one of the most common errors, however, because the sending party does not send the/r/n, causing the data to be unreadable. Other common errors include the absence of initialization of the receive buffer causing character garbled, not being reassembled according to the read in to the byte number, resulting in an exception to the data received. So the code shows what is called byte-Sending and bytes-accepted, which is a very important concept and principle in network programming. Let those input stream println () method and output stream ReadLine () method go to Hell, not bad, but I suggest you not to use, because those will hinder your network programming the essence of understanding and understanding. I would also like to make a special note: sometimes flush () is really not necessary unless you use a buffered input and output stream to read and write bytes.

Server-side code:

Package com.gloomyfish.socket.tutorial.two; 
Import Java.io.DataOutputStream; 
Import java.io.IOException; 
Import Java.net.ServerSocket; 
 
Import Java.net.Socket; 
  public class HelloService extends Thread {private ServerSocket serversocket; 
  public HelloService (int port) throws IOException {ServerSocket = new ServerSocket (port); public void Run () {try {while (true) {System.out.println (' Waiting for client ' on PO 
        RT "+ Serversocket.getlocalport ()); Socket client = Serversocket.accept (); Blocked & Waiting for income socket SYSTEM.OUT.PRINTLN ("Just connected to" + client.getremotesocketaddres 
        s ()); 
        DataOutputStream dos = new DataOutputStream (Client.getoutputstream ()); 
        byte[] Hello = "Hello, Java Socket". GetBytes (); 
        Dos.write (Hello, 0, hello.length); 
        Dos.close (); 
      Client.close (); 
    } catch (Exception e) {e.printstacktrace (); }} PUBlic static void Main (string[] args) {try {HelloService service = new HelloService (9999); 
    Service.start (); 
    catch (IOException e) {e.printstacktrace (); 
 } 
  } 
}

The

Server listens on port 9999 and waits for a connection, using Java thread to implement server-side startup.
Client code is as follows:

Package com.gloomyfish.socket.tutorial.two; 
Import Java.io.DataInputStream; 
Import java.io.IOException; 
Import java.net.InetSocketAddress; 
Import Java.net.Socket; 
 
Import java.net.SocketAddress; 
  public class Helloclient {private int clientnumber; 
  Private socketaddress address; 
  Public helloclient (int clientnum) {clientnumber = Clientnum; public void Setupclients (String serverhostname, int port) throws IOException {address = new Inetsocketaddre 
    SS (Serverhostname, Port); 
      for (int i=0; i<clientnumber; i++) {System.out.println (); 
      System.out.println ("Start client No." + (i+1)); 
      Socket socket = new socket (); 
      Socket.connect (address); 
      DataInputStream BufferedReader = new DataInputStream (Socket.getinputstream ()); 
      byte[] Cbuff = new byte[256]; 
      char[] Charbuff = new char[256]; 
      int size = 0; while (size = Bufferedreader.read (cbuff)) > 0) {convertbytetochar (Cbuff, Charbuff, size); 
      System.out.println (Charbuff); 
      } bufferedreader.close (); 
    Socket.close (); } private void Convertbytetochar (byte[] cbuff, char[] charbuff, int size) {for (int i=0; i<charbuff.le Ngth; 
      i++) {if (I < size) {Charbuff[i] = (char) cbuff[i]; 
      } else {charbuff[i] = '; }} public static void Main (string[] args) {try {helloclient client = new Helloclient (1 
      0); 
    Client.setupclients ("localhost", 9999); 
    catch (IOException e) {e.printstacktrace (); 
 } 
  } 
}

10 clients are started to connect to the server side, and the client closes the connection after receiving the server-side greeting.
Special Note: Be sure to initialize buffer Charbuff
Program Run Result:

The above is the entire content of this article, I hope to help you learn.

Related Article

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.