0

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, but 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,

asked Nov 30, 2010 at 4:24
0

1 Answer 1

7

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.

answered Nov 30, 2010 at 5:50
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, EJP, you've been a great help! Creating the output stream first on both ends worked perfectly!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.