Skip to content

Instantly share code, notes, and snippets.

@SAFAD
Forked from anonymous/gist:9771388
Last active August 29, 2015 13:57
Show Gist options
  • Save SAFAD/9771548 to your computer and use it in GitHub Desktop.
Save SAFAD/9771548 to your computer and use it in GitHub Desktop.
package server;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author Rashid
*/
public class Server {
public static void main(String[] args ) throws Exception{
String clientSentence;
String capitalizedSentence;
// Creating Server Port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
System.out.println("Server Started and listening to the port 6789");
//always use try-catch to catch issues and trouble rather than crashing your apps.
//also use finally to close the connection after closing the server, or it will keep running
try{
while(true) {
/*This part looks TOO COMPLEX, i am going to improve it
// The server accepts the waiting client
Socket connectionSocket = welcomeSocket.accept();
// IN
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); // OUT
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
*/
Socket socket = welcomeSocket.accept();
//again try-catch-finally is essential here too
try{
// READ LINE
//clientSentence = inFromClient.readLine();
//INPUT and OUTPUT Streams..
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
clientSentence = in.readLine();
if (input == null || input.equals(".")) {
break;
}
// UPPER CASE
capitalizedSentence = clientSentence.toUpperCase() + '\n';
out.println(capitalizedSentence);
//outToClient.writeBytes(capitalizedSentence);
}
catch (IOException e) {
System.out.println("An error has occured : " + e);
}
finally{
socket.close();
}
}
}
finally{
welcomeSocket.close();
}
}
}
package tcp;
import java.io.*;
import java.net.*;
public class TCP {
public static void main(String[] args) throws Exception {
String Sentence;
String modifiedSentence;
// File Reading
//-----------------
// -----------------
// Open Connection to the Port 6789
// First Parameter is Server-Address and Second: is the Port
Socket clientSocket = new Socket("localhost",6789);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
PrintWriter toServer = new PrintWriter(clientSocket.getOutputStream(), true);
toServer.println(inFromUser);
BufferedReader fromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
while (true) {
if (fromServer.readLine() != null) {
System.out.println("Server response : " + fromServer.readLine());
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment