当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Is there a way to determine which OutputStream is currently sending through to my sockets inputstream?

问题描述:

This is my client right now:

@Override

public void run()

{

try

{

@SuppressWarnings("resource")

InputStream socketIn = socket.getInputStream();

Scanner in = new Scanner(socketIn);

PrintWriter out = new PrintWriter(socket.getOutputStream());

ObjectInputStream oin = new ObjectInputStream(socketIn);

gui = new GuiController(out);

while (true)

{

System.out.println(socketIn);

if(in.hasNext()){

gui.updateResponse(in.nextLine());

}

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

As you can see, I have both an ObjectInputStream as well as a Scanner. This is because I am both sending simple Strings from my Server, which should be caught by the string, as well as Hashtable-Objects, which are dealt by the ObjectInputStream.

However, now I need to determine whether my Servers PrintWriter or ObjectOutputStream sent the data, so I can react to it. If I don't make any check, my Scanner will just grab the object and print it as a string, which is obviously very wrong.

I need something like this:

if(socketIn.origin == ObjectOutputStream){

}

else{

}

Note that this is just some pseudo code, but I think you get the idea.

网友答案:

Disclaimer: This is certainly not the recommended way of doing this for that look at EJP's answer.

But what you could do: Before you send anything through your object stream or string stream, send a string through the string stream telling the client what to expect. After that you send the actual data via either the string stream or the object stream. So in pseudocode this would be:

read string with string input stream
if string==object then
    read data with object input stream
    handle object
else if string==string
    read data with string input stream
    handle string

This would work as you first receive what is coming, and then you read the actual data.

For the sake of completeness here's the pseudo code for the sender:

if the data to send==object
    print 'object' to the string output stream
    print object to the object ouput stream
else if data to send==string
    print 'string' to the string output stream
    print data string to the string ouput stream

I hope this helps you :)

NOTE: Be very carefull doing this when your socket is used by multiple threads.

NOTE: You could also wrap your string in an object and just send it through the object stream.

网友答案:

No. There is only one data stream. This will never work, for a number of reasons. Use a single stream, or reader/writer pair, or DataInput/OutputStream pair, or ObjectInput/OutputStream pair.

分享给朋友:
您可能感兴趣的文章:
随机阅读: