captain monk
captain monk

Reputation: 727

Java Client/Server send or get int or string type

i'm trying to create a simple java program where the client and the server will be both able to send and get strings and ints. I can do it work with only strings or only ints but i find it hard to combine them without making a mess. If someone can tell me the easiest way to do it i would be thankfull. Here is what i've done till now but it gives the wrong number back.

MyServer.java

package myserver;

import java.io.DataInputStream;
import java.util.Random;
import java.io.*;
import java.net.*;


public class MyServer 
{
   public static void main(String argv[]) throws Exception
      {
            String clientSentence;
            String answer;
            ServerSocket welcomeSocket = new ServerSocket(6789);
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            Random rand = new Random();
            int  n = rand.nextInt(100) + 1;
            System.out.println("Received: " + clientSentence);
            answer = "Hey " + clientSentence + " guess a number from 1 to 100!" + '\n';
            outToClient.writeBytes(answer);
             DataInputStream integerFromClient = new DataInputStream(connectionSocket.getInputStream());
            int k = integerFromClient.readInt();
            System.out.println(k);

      }
} 

MyClient.java

package myserver;

import java.io.*;
import java.net.*;

class MyClient
{
 public static void main(String argv[]) throws Exception
 {
  String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", 6789);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("SERVER: " + modifiedSentence);
  int k = inFromUser.read();
  outToServer.writeInt(k);
  clientSocket.close();
 }
}

Upvotes: 0

Views: 10947

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533442

I suggest you use DataInputStream/DataOutputStream wrapped around BufferedInputStream/BufferedOutputStream. This will allow you to send

dos.writeUTF(string);
String s = dis.readUTF();

or

dos.writeInt(n);
int i = dis.readInt();

if you don't know what type you are going tow rite you can use a byte like this.

dos.writeByte('S');
dos.writeUTF(string);
dos.writeByte('i');
dos.writeInt(n);

and

for(int code; (code = dis.read()) != -1;) {
   switch(code) {
      case 'S':
            String s = dis.readUTF();
            process(s);
            break;
      case 'i':
            int i = dis.readInt();
            process(i);
            break;
      default:
            throw new StreamCorruptedException("code: "+code);
   }

}

You can extend this to sending complex data structures.

Upvotes: 1

f1sh
f1sh

Reputation: 11934

The "mess" in this case is just your message structure. You are sending the raw value over the socket with no information about what the value is, this makes it hard for the recipient to determine what data the value might be. I guess that is the main problem.

I would suggest that you pick a pre-existing format that lets you combine data types into one message. I would suggest JSON or xml, which are (un)marshallable very easily with a respective library.

Otherwise you could look into something simpler like the bencoding structure, combining the int 3 and the string "hello" into one message would look like this:

i3e5:hello

Upvotes: 0

Related Questions