Skip to content

Instantly share code, notes, and snippets.

@kamilbolka
Created February 4, 2019 19:24
Show Gist options
  • Save kamilbolka/8a25723c3f604d3759db3fb69c323779 to your computer and use it in GitHub Desktop.
Save kamilbolka/8a25723c3f604d3759db3fb69c323779 to your computer and use it in GitHub Desktop.
Example of Socket and ServerSocket on local host connection
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockets;
import java.net.Socket;
import java.io.*;
import java.util.Arrays;
/**
*
* @author kamil
*/
public class Client {
private Socket socket;
private BufferedReader input;
private PrintWriter output;
private String prefix = "[Clinet] >> ";
public Client(String ip, int port) {
try {
// Establish a connection
socket = new Socket(ip, port);
System.out.println(prefix + "Connected!");
// Take input from the termianl
input = new BufferedReader(new InputStreamReader(System.in));
// Send output to the socket
output = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(prefix + "ERROR!");
System.out.println(e.getMessage());
}
// Give termianl access
showTermianlAccess();
}
private void showTermianlAccess() {
String line = "";
String[] cmdList = {Command.quit.toString(), Command.send.toString() + " <message>"};
try {
while (line.equalsIgnoreCase(Command.quit.toString()) == false) {
// Take input from the termianl
System.out.println(prefix + "Commands > " + Arrays.toString(cmdList));
line = input.readLine();
// Check if the first words is a send commands
String[] splitLine = line.split(" ");
if (splitLine.length > 1 && splitLine[0].equalsIgnoreCase(Command.send.toString())) {
// Send the message to the socket
output.println(splitLine[1]);
System.out.println("Message send!\n");
} else {
System.out.println("Input Error! Try again\n");
}
}
} catch (IOException e) {
System.out.println(prefix + "Error!");
System.out.println(e.getMessage());
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockets;
/**
*
* @author kamil
*/
public enum Command {
quit("Quit"), send("Send");
private String msg;
private Command(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return msg;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockets;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
/**
*
* @author kamil
*/
public class Server {
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader input;
private PrintWriter output;
private String prefix = "[Server] >> ";
public Server(int port) {
try {
// Create a server socket
serverSocket = new ServerSocket(port);
System.out.println(prefix + "Server is starting...");
System.out.println(prefix + "Server is waiting for a client...");
// Wait until a connection from a clinet
socket = serverSocket.accept();
System.out.println(prefix + "Server is connected to the client!");
// Load input and output
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(prefix + "Server Error!");
System.out.println(e.getMessage());
}
runServerClientCommunication();
}
private void runServerClientCommunication() {
String line = "";
try {
while (line.equalsIgnoreCase(Command.quit.toString()) == false) {
// Read input from client
line = input.readLine();
System.out.println(prefix + "Client said: " + line);
}
// Close the ports
System.out.println(prefix + "Closting connection!");
input.close();
output.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println(prefix + "Server Error!");
System.out.println(e.getMessage());
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockets;
/**
*
* @author kamil
*/
public class StartServerClient {
private static final String IP = "127.0.0.1"; // Local host
private static final int PORT = 5000;
public static void main(String[] args) {
// Start the server fist on new thread
new Thread(new Runnable() {
@Override
public void run() {
new Server(PORT);
}
}).start();
// Delay
try {Thread.sleep(2000);} catch (Exception e) {}
// Start the clinet on a new thread
new Thread(new Runnable() {
@Override
public void run() {
new Client(IP, PORT);
}
}).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment