Skip to content

Instantly share code, notes, and snippets.

@skayred
Created October 18, 2011 14:12
Show Gist options
  • Save skayred/1295512 to your computer and use it in GitHub Desktop.
Save skayred/1295512 to your computer and use it in GitHub Desktop.
Server
package com.skalar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server(int port) {
calculator = new PostfixCalculator();
in = null;
out = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port: " + port);
return;
}
}
public void startServer() {
try {
System.out.print("Waiting for a client...");
fromClient = serverSocket.accept();
System.out.println("Client connected");
} catch (IOException e) {
System.out.println("Can't accept");
return;
}
try {
in = new BufferedReader(new InputStreamReader(
fromClient.getInputStream()));
out = new PrintWriter(fromClient.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
String input;
try {
System.out.println("Wait for messages");
while ((input = in.readLine()) != null) {
if (input.equalsIgnoreCase("exit"))
break;
out.println(calculator.calculateFromInfix(input));
System.out.println(input);
}
out.close();
in.close();
fromClient.close();
serverSocket.close();
} catch (IOException exc) {
exc.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server(3000);
server.startServer();
}
private PostfixCalculator calculator;
private BufferedReader in;
private PrintWriter out;
private ServerSocket serverSocket;
private Socket fromClient;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment