[Java] TCP communication with Java (Socket communication) (ASCII, Binary)

4 minute read

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){

// Accept 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();

// I/O reader/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 termination");

} 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"; //Destination
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("Enter a command");
System.out.println("-------------------");

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

if(sendMSG.isEmpty()) {
        System.out.println("↓↓ Somewhat strange ↓↓");
        continue;
        }

out.write(sendMSG);
out.flush();
//Leave the loop by inputting bye
if (sendMSG.equals("bye")) {
break;
}

// receive a string from the 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 exit");

} 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 client input");

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

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

os = socket.getOutputStream();//End the loop with the input of infinite loop 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("Character typed at 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 termination");
} 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 socket on the client side 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 client to server
writer = new PrintWriter
(cSocket.getOutputStream(), true);

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

//End the loop with the input of infinite loop bye
String line = null;
String read = null;
while (true) {
System.out.println("-------------------");
System.out.println("Enter a command");
System.out.println("-------------------");

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

// Send the character for sending
if(line.isEmpty()) {
System.out.println("↓↓ Somewhat strange ↓↓");
continue;
}

writer.println(bi);
//Leave the loop by inputting 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 exit");
}
}
}