-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPServer.java
More file actions
95 lines (77 loc) · 2.36 KB
/
TCPServer.java
File metadata and controls
95 lines (77 loc) · 2.36 KB
1
import java.io.*; import java.net.*; import java.lang.*;public class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String keyword; String getNum; String setNum; HashMap<String,String> directory = new HashMap<String,String>(); ServerSocket welcomeSocket = new ServerSocket(6791); Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); while(true) { clientSentence = inFromClient.readLine().split(" "); keyword = clientSentence[0]; if (keyword.equals("CHECK:")) { if (clientSentence.length < 2){ outToClient.writeBytes( "Correct format is CHECK: $NAME\n"); } else{ getNum = directory.get(clientSentence[1]); if (getNum != null){ outToClient.writeBytes( clientSentence[1] + "'s number is " + getNum + "\n"); } else{ outToClient.writeBytes( "Sorry, name not found, please try again\n"); } } } else if (keyword.equals("ADD:")) { if (clientSentence.length < 3){ outToClient.writeBytes( "Correct format is ADD: $NAME $NUMBER\n"); } else{ setNum = directory.get(clientSentence[1]); if (getNum == null){ directory.put(clientSentence[1], clientSentence[2]); outToClient.writeBytes(clientSentence[1] + " added\n"); } else{ outToClient.writeBytes( "Sorry, that name is already in the directory\n"); } } } else if (keyword.equals("LIST")){ for(Map.Entry<String, HashMap> entry : directory.entrySet()) { String key = entry.getKey(); HashMap value = entry.getValue(); outToClient.writeBytes( key + ": " + value + "\n"); } else if (keyword.equals("DELETE")){ //Delete an entry } else if(keyword.equals("END")) { break; } else { outToClient.writeBytes("Command not recognised, please try again\n"); } } } }