Here is a simple example of TCP Server using java. It gives you idea about how TCP server opens up a port and receives message from TCP client.
To compile this code, simply install Java JDK to your computer. Then save this code with file name Server.java and then open terminal. Change your directory to where you save this file and type in javac Server.java - this will create new file Server.class, don't do anything with .class file unless you'll get an error: "Exception in thread "main" java.lang.NoClassDefFoundError". And then type in terminal java Server .
Next post will be a simple Java TCP Client.
#source: https://systembash.com/a-simple-java-tcp-server-and-tcp-client/
To compile this code, simply install Java JDK to your computer. Then save this code with file name Server.java and then open terminal. Change your directory to where you save this file and type in javac Server.java - this will create new file Server.class, don't do anything with .class file unless you'll get an error: "Exception in thread "main" java.lang.NoClassDefFoundError". And then type in terminal java Server .
import java.io.*; import java.net.*; import java.util.Scanner; class Server{ private static Server server; static int serverPort = 1234; static ServerSocket welcomeSocket; public Server(){ try{ welcomeSocket = new ServerSocket(setSocket()); }catch(Exception e){ System.out.println("Error: "+e.getMessage()); } } private int setSocket(){ Scanner in = new Scanner(System.in); System.out.print("Enter socket number:"); serverPort = in.nextInt(); System.out.println("Socket number "+serverPort+" created."); System.out.println("Listening..."); return serverPort; } public static void main(String argv[]) throws Exception { server = new Server(); String clientSentence; String capitalizedSentence; while(true){ Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); System.out.println("Received: " + clientSentence); capitalizedSentence = clientSentence.toUpperCase() + " from "+serverPort+'\n'; outToClient.writeBytes(capitalizedSentence); } } }
Next post will be a simple Java TCP Client.
#source: https://systembash.com/a-simple-java-tcp-server-and-tcp-client/
Comments
Post a Comment