This article explains the detailed code of Java Socket programming to implement a simple greeting service for your reference. The specific content is as follows
Server side:
Implementing the simplest Hello service, print out the client IP address to the console, send a string of characters (Hello, Java Socket) to any connected client and close the connection with the client. Wait for the next client's connection request to arrive.
Client:
Implement a simplest Socket to connect to Hello server, accepts byte data sent by the server and prints the content to the console.
Key tips:
Because JAVA provides a lot of input and output stream APIs, many beginners are exposed to JAVA SOCKET programming, and because they lack understanding of the nature of network byte communication, they directly accept Socket byte streams by readline(). However, because the sending party does not send /r/n, the data cannot be read. This is the most common error. Some other common mistakes include not initializing the accept buffer, resulting in garbled characters, and not reassembled according to the number of bytes received by reading, resulting in an exception to the received data. So the code demonstrates what is sent by byte and acceptance by byte. This is a very important concept and principle in network programming. Let the input stream println() method and output stream readline() method go to the hell. It’s not that it’s not easy to use, but I suggest you don’t use it because those will hinder your understanding and understanding of the essence of network programming. Also, I would like to make a special note: sometimes flush() is 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 port " + serverSocket.getLocalPort()); Socket client = serverSocket.accept(); // blocked & waiting for income socket System.out.println("Just connected to " + client.getRemoteSocketAddress()); 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 connection, and uses Java Thread to achieve server-side startup.
The 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.SocketAddress; import java.net.SocketAddress; public class HelloClient { private int clientNumber; private SocketAddress address; public HelloClient(int clientNum) { clientNum = clientNum; } public void setupClients(String serverHostName, int port) throws IOException { address = new InetSocketAddress(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.length; i++) { if(i < size) { charBuff[i] = (char)cbuff[i]; } else { charBuff[i] = ' '; } } } public static void main(String[] args) { try { HelloClient client = new HelloClient(10); client.setupClients("localhost", 9999); } catch (IOException e) { e.printStackTrace(); } } } Start 10 clients to connect to the server side, and after receiving the server greeting, the client closes the connection.
Special tip: Be sure to initialize the buffer charBuff
Program running results:
The above is all about this article, I hope it will be helpful to everyone's learning.