开发者

java object streams

开发者 https://www.devze.com 2023-01-27 18:31 出处:网络
I\'m trying to create a server in java which will maintain up to 4 connections simultaneously.I thought that holding the relevant information in an array would serve my purpose, well, bu开发者_如何学编

I'm trying to create a server in java which will maintain up to 4 connections simultaneously. I thought that holding the relevant information in an array would serve my purpose, well, bu开发者_如何学编程t I'm having some trouble.

Here is the class I've created:


import java.net.*;
import java.io.*;
public class tcpConnects{
private ObjectInputStream input;
private ObjectOutputStream output;
private int player;
public tcpConnects(int playerNumber, Socket connect) {
    // TODO Auto-generated method stub
        try{
            System.out.println("create InputStream");
            input= new ObjectInputStream(connect.getInputStream());
            System.out.println("create OutputStream");
            output= new ObjectOutputStream(connect.getOutputStream());
            System.out.println("streams created");
            //sendData("Welcome!");
            player=playerNumber;
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
    public ObjectInputStream getInput(){
        return input;
    }
    public void setInput(ObjectInputStream in){
        input=in;
    }
    public ObjectOutputStream getOutput(){
        return output;
    }
    public void setOutput(ObjectOutputStream out){
        output=out;
    }
    public int getPlayer(){
        return player;
    }
    public void sendData(String data){
        try{
            output.writeObject(data);
            output.flush();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }
}

anyway, when I send a socket into the class, it gets to the stage of creating the input stream, but then the stream is never actually created. The syntax appears to be correct, so I can only assume that there is some form of logic error which I am not aware of. Any help in deciphering why this class will not create an input or output stream would be greatly appreciated.

Thanks,


Create the ObjectOutputStream before the ObjectInputStream, at both ends. The constructor of ObjectOutputStream writes a header to the stream that the constructor of ObjectInputStream reads, so if you create the ObjectInputStreams first you get a deadlock.

0

精彩评论

暂无评论...
验证码 换一张
取 消