Hi) How can I make the calculation between the client and the server using UDP protocol?

For example, the server sends the expression 1 + 2. The client receives this message, and he responds to server 3. Here is the code listing, if necessary:

import java.net.*; import java.io.File; class kurs { public static int serverPort = 666; public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; public static byte buffer[] = new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while(true) { int c=System.in.read(); switch(c){ case -1: System.out.println("Server Quits."); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort)); pos=0; break; default: buffer[pos++]=(byte)c; } } } public static void TheClient() throws Exception{ while(true) { DatagramPacket p = new DatagramPacket(buffer,buffer.length); ds.receive(p); System.out.println(new String(p.getData(),0,p.getLength())); } } public static void main(String args[]) throws Exception{ if(args.length==1){ ds = new DatagramSocket(serverPort); TheServer(); } else{ ds=new DatagramSocket(clientPort); TheClient(); } } } 
  • There is another idea, for example, a command is sent to the server, 1. Then it calculates the expression 2 + 2 = 4. How to implement? - marioxxx
  • Thanks for answers. The question is closed, made in C #. - marioxxx 5:57 pm

1 answer 1

Gee-gee, and the teacher at you with imagination!

The solution pattern is:

  1. Client sends string
  2. Server accepts string
  3. The string is inserted into the parser - parser. The analyzer builds a syntax tree which actually gives the answer what is 2 + 1
  4. The result is sent back to the client as a string.
  5. Client receives string and prints

In general, the most difficult and interesting thing here is just writing a parser :)

  • If the client knows that there will be an addition of numbers) - marioxxx
  • But what's the difference - the parser will return a syntax error and that's it. - Barmaley