TCP communication (socket communication) in Java (ASCII, Binary)

ASCII

Server

ASCII-Server



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerASCII {

        //Use port 80
		private static final int LISTEN_PORT = 80;
		public static void main(String[] args){

			//Receiving socket
			Socket socket =null;

			//Passive socket(Server socket)
			ServerSocket ss_socket = null;
			try {
				ss_socket = new ServerSocket(LISTEN_PORT);
			    } catch (IOException e1) {
				//TODO auto-generated catch block
				e1.printStackTrace();
			    }

			//Write server-side processing
			try{

				System.out.println("Waiting for client");

				socket = ss_socket.accept();

				//Input / output reader and writer
				BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

				while (true) {
				char[] buf = new char[1024];
				if(in.read(buf) != -1){
					try{
						System.out.println("receive↓↓");
						System.out.print(buf);
						Thread.sleep(250);
		            }
		            catch(Exception ex){
		                ex.printStackTrace();
		            }
				}
				System.out.print("\n");

				if (buf.equals("bye")) {
	                break;
	        	}

				out.write(buf);
				out.flush();
				}

			}catch(IOException err){
				err.printStackTrace();
			}finally{
				try{
					if (socket!=null){
						socket.close();
					}
					if (ss_socket!=null){
						ss_socket.close();
					}
					System.out.println("Server side end");

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	    }
 }

Client

ASCII-Client



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientASCII {

	private static final String HOST = "localhost";//access point
	private static final int PORT = 80;//Use port 80
	private static final String err = "0000";

	public static void main(String[] args) throws InterruptedException {
		ClientASCII aa = new ClientASCII();
		aa.Cascii();

	}

	public void Cascii() throws InterruptedException{
		Socket socket = null;
		try {
			socket = new Socket(HOST,PORT);
		} catch (UnknownHostException e1) {
			//TODO auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			//TODO auto-generated catch block
			e1.printStackTrace();
		}
		try{
			//Incoming and outgoing readers and writers
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			BufferedReader csInput = new BufferedReader (new InputStreamReader(System.in));

			while (true) {
			System.out.println("-------------------");
			System.out.println("Please enter the command");
			System.out.println("-------------------");

			//Message to send to server
			String sendMSG = csInput.readLine();
			String sub;
			String check;

			if(sendMSG.isEmpty()) {
        		System.out.println("↓ ↓ Something is wrong ↓ ↓");
        		continue;
        	}

			out.write(sendMSG);
			out.flush();
			//Break out of the loop by typing bye
			if (sendMSG.equals("bye")) {
				break;
			}

			//Receive string from server
			System.out.print("receive->");
			char[] buf = new char[1024];
			if(in.read(buf) != -1){
				System.out.print(buf);
				System.out.println("\n");
	    		sub = new String(buf);

				if(!check.equals(err)) {
					System.out.println("Error occurred");
				}
			} else {
				System.out.println("return is null");
				break;
			}
			}

		}catch(IOException err){
			err.printStackTrace();
		}finally{
			try {
				if (socket != null) {
					socket.close();
				}
		        System.out.println("Client side end");

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Binary

Server

Binary-Server


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.codec.binary.Hex;

public class ServerBinary {

	public static void main(String[] args) {

		ServerBinary s1 = new ServerBinary();
		s1.runSample();

	}

	void runSample() {

		ServerSocket sSocket = null;
		Socket socket = null;
		BufferedReader reader = null;
		PrintWriter writer = null;
		OutputStream os = null;
		byte crlf [] = {13,10};

		try{
			//Create a server-side socket by specifying the IP address and port number
			sSocket = new ServerSocket();
			sSocket.bind(new InetSocketAddress
					("localhost",8000));

			System.out.println("Waiting for input from client");

			//Continue to wait for requests from clients
			socket = sSocket.accept();

			//For receiving from clients
			reader = new BufferedReader(
					new InputStreamReader
					(socket.getInputStream()));

			os = socket.getOutputStream();

			//Infinite loop Exit the loop by inputting bye
			String line = null;
	        while (true) {

	        	line = reader.readLine();
	        	byte[] sbyte = line.getBytes();
	        	String ddd = new String(Hex.encodeHex(sbyte));

	        	if (line.equals("bye")) {
	                break;
	        	}
		        os.write(sbyte);
		        os.write(crlf);

	            System.out.println("Characters entered on the client =" + ddd);
	        }
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if (reader!=null){
					reader.close();
				}
				if (socket!=null){
					socket.close();
				}
				if (sSocket!=null){
					sSocket.close();
				}
	            System.out.println("Server side end");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Client

Binary-Client


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import org.apache.commons.codec.binary.Hex;

public class ClientBinary {

	public static void main(String[] args) {

		ClientBinary s2 = new ClientBinary();
		s2.runSample();
	}

	void runSample() {

		Socket cSocket = null;
		BufferedReader csInput = null;
		PrintWriter writer = null;
		BufferedReader reader = null;

		try{
			//Create a client-side socket by specifying the IP address and port number
			cSocket = new Socket("localhost", 8000);

			//For input on the client side
			csInput = new BufferedReader
					(new InputStreamReader(System.in));

			//For sending from the client side to the server
			writer = new PrintWriter
					(cSocket.getOutputStream(), true);

			//For receiving from the server side
			reader = new BufferedReader
					(new InputStreamReader
							(cSocket.getInputStream()));

			//Infinite loop Exit the loop by inputting bye
			String line = null;
			String read = null;
			while (true) {
				System.out.println("-------------------");
				System.out.println("Please enter the command");
				System.out.println("-------------------");

	        	line = csInput.readLine();
	        	byte[] bi = line.getBytes();

				//Send characters for sending
	        	if(line.isEmpty()) {
	        		System.out.println("↓ ↓ Something is wrong ↓ ↓");
	        		continue;
	        	}

	        	writer.println(bi);
				//Break out of the loop by typing bye
				if (line.equals("bye")) {
					break;
				}

				read = reader.readLine();
				byte[] sbyte = read.getBytes();
				String ddd = new String(Hex.encodeHex(sbyte));
				System.out.println("return: " + ddd);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if (reader != null) {
					reader.close();
				}
				if (writer != null) {
					writer.close();
				}
				if (csInput != null) {
					csInput.close();
				}
				if (cSocket != null) {
					cSocket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
	        System.out.println("Client side end");
		}
	}
}

Recommended Posts

TCP communication (socket communication) in Java (ASCII, Binary)
ASCII art in Java
Read binary files in Java 1
Read binary files in Java 2
Create variable length binary data in Java
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Display text as ASCII art in Java (jfiglet)
TCP communication material
Pi in Java
FizzBuzz in Java
Enable / disable SNI in Java for each communication
Summary of Java communication API (1) How to use Socket
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
"Hello World" in Java
Callable Interface in Java
Comments in Java source
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Java Network Basics (Communication)
Zabbix API in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
How to use JSON data in WebSocket communication (Java, JavaScript)
Socket communication with a web browser using Java and JavaScript ②
Socket communication with a web browser using Java and JavaScript ①