Plain String UTF-8 communication on the net - Java Network

Java examples for Network:ServerSocket

Description

Plain String UTF-8 communication on the net

Demo Code



import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

public class Server {
    private static final Logger logger = LogManager.getLogger(Server.class);
    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
        if (args.length != 1) {
            System.err.println("Usage: java Server <port number>");
            System.exit(1);//  w w  w.  j  a  va  2  s  .com
        }
        int portNumber = Integer.parseInt(args[0]);
        logger.trace("Sever started");

        ServerSocket serverSocket;
        Socket clientSocket;
        DataInputStream in;

        try {
            serverSocket = new ServerSocket(portNumber);
            clientSocket = serverSocket.accept();

            in = new DataInputStream(clientSocket.getInputStream());
            String received2 = in.readUTF();

            logger.trace("received " + received2);
        } catch (Exception e ) {
            e.printStackTrace();
        }
    }
}

Related Tutorials