A simple TCP Socket calculator

A simple TCP Socket calculator

 

//Server Class

public class SimpleServer {
public static void main(String args[]) throws IOException {
// Register service on port 1254
ServerSocket s = new ServerSocket(1251);
Socket s1=s.accept(); // Wait and accept a connection
// Get a communication stream associated with the socket

InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
int num1 = (dis.readInt());
int num2 = (dis.readInt());
String operation = (dis.readUTF());
int ans = 0;
if (operation.equals(“add”) == true){
ans = num1 + num2;
}
else if (operation.equals(“sub”)){
ans = num1 – num2;
}
// Close the connection, but not the server socket
dos.close();
s1out.close();
s1.close();
}
}

 

//Client Class

public class SimpleClient {
public static void main(String args[]) throws IOException {
// Open your connection to a server, at port 1254
Socket s1 = new Socket(“localhost”,1251);
// Get an input file handle from the socket and read the input
Scanner scanln = new Scanner(System.in);

//System.out.println(“Enter number1: “);
//int num1 = scanln.nextInt();

//System.out.println(“Enter number2: “);
//int num2 = scanln.nextInt();

System.out.println(“Search Movie: “);
String searchmovie = scanln.next();

OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream (s1out);
//dos.writeInt(num1); //send to server6
//dos.writeInt(num2); //send to server6
dos.writeUTF(searchmovie);
//dos.writeInt(operation); //send to server6

//GUI.HomeMenu.homeMenu=new GUI.HomeMenu();
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = new String (dis.readUTF());

System.out.println(“” + st);
// When done, just close the connection and exit
dis.close();
s1In.close();
s1.close();
}
}

4 thoughts on “A simple TCP Socket calculator

    1. Whithout importing swing just import awt tools for the Client classic, how would the code look like for the Client

Please Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s