Created
November 7, 2020 10:07
-
-
Save tinshade/98c32652ae209048f6f954a9d63b74ad to your computer and use it in GitHub Desktop.
A simple Java Server to allow socket connections. Port forwarding the local port can allow of TCP message transmission!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.util.Scanner; | |
public class JavaServer { | |
public static void main(String[] args) { | |
connectToServer(); | |
} | |
public static void connectToServer() { | |
//Try connect to the server on an unused port eg 9991. A successful connection will return a socket | |
try(ServerSocket serverSocket = new ServerSocket(9991)) { | |
Socket connectionSocket = serverSocket.accept(); | |
//Create Input&Outputstreams for the connection | |
InputStream inputToServer = connectionSocket.getInputStream(); | |
OutputStream outputFromServer = connectionSocket.getOutputStream(); | |
Scanner scanner = new Scanner(inputToServer, "UTF-8"); | |
PrintWriter serverPrintOut = new PrintWriter(new OutputStreamWriter(outputFromServer, "UTF-8"), true); | |
serverPrintOut.println("I'm up!\nType 'over' to terminate."); | |
//Have the server take input from the client and echo it back | |
//This should be placed in a loop that listens for a terminator text e.g. bye | |
boolean done = false; | |
while(!done && scanner.hasNextLine()) { | |
String line = scanner.nextLine(); | |
serverPrintOut.println("Server: " + line); | |
if(line.toLowerCase().trim().equals("over")) { | |
done = true; | |
} | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment