Results 1 to 3 of 3

Thread: Thread and I/O

  1. #1
    MicIn is offline Member
    Join Date
    Jan 2011
    Posts
    2
    Rep Power
    0

    Default Thread and I/O

    Hi, all,
    I have a question that needs assistance.
    I have written
    1) a Java swing program that send a string using DataInputStream.readUTF() and also a few integer using DataInputStream.readInt() continuously using Threads.
    2) The Java swing program will send to another Java program that will process those string and integer through a socket by continuing to listen to port 12345 and ip address 127.0.0.1 in an never-ending thread.

    It was alright at the start but as the program goes, I got a EOFException caught by the program that acts as a server for one of the integer sent by the Java swing program.

    May I know what could have caused this problem? I am new to Threads and I/O. One more thing, I am quite confused with my concept in I/O. For example, in my case, how do Java send string and integer to the other program. Do the program send them all together or do they send those data one by one? If they send them one by one, how to make the Java program send them altogether because I need them so that the other program can process and exception (for example, EOFException)will be thrown if one of the data is missing.

    Thank you in advance for assistance.

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    6

    Default

    I recommend posting an SSCCE that demonstrates the problem.

  3. #3
    MicIn is offline Member
    Join Date
    Jan 2011
    Posts
    2
    Rep Power
    0

    Default

    This is my school assignment. I am supposed to write a Java swing program that acts as a client and connect to another Java program that acts as a server which is multithreaded and listening at port 12345. The server is for playing the addition game.

    So my client have a play button to start the game and below is my code and I actually started my thread for socket connection and then the play button will be disabled. Until the question is shown on screen which I got it from the server, no button is enabled. When the question is shown, underneath, there is a textfield for user to enter their answer and also a submit button for user to press. In my program, my thread actually continues in the background, when the user press the submit button, boolean submitted will be true(as highlighted) :

    Java Code:
    new Thread(){
    			public void run()
    			{
    				while (true) 
    				{
    					if (endThread == true)
    					{
    						break;
    					}
    					try 
    					{
    						if (getStatus().equals("Found"))
    						{
    							setStatus("Connected");
    						}
    					    s = new Socket("127.0.0.1", 12345);
    					   	output=s.getOutputStream();
    					    input=s.getInputStream();
    					    dout= new DataOutputStream(output);
    					    din= new DataInputStream(input);
    					  [COLOR="Yellow"]  if (submitted == true)[/COLOR]
    					    {
    					    	setStatus("Submitted");
    					    }
    						dout.writeUTF(getStatus());
    						if (getStatus().equals("Left"))
    						{
    							statusTxtField.setText("The other player has gone.\nPress play to start the game again");
    							playBtn.setEnabled(true);
    						    ansTxtField.setEditable(false);
    						    submitted = false;
    				        	ansBtn.setEnabled(false);
    				        	setStatus("Initiated");
    						    endThread = true;
    						    setSessionId(0);
    						    setUserNo(0);
    						}
    						else
    						{
    							dout.writeInt(getSessionId());
    							dout.writeInt(getUserNo());
    							if (getStatus().equals("Submitted"))
    							{
    								dout.writeInt(answer);
    							}
    							setStatus(din.readUTF());
    							setSessionId(din.readInt());
    							setUserNo(din.readInt());
    							System.out.println(getStatus()+"1223");
    							System.out.println(getSessionId()+" SESS");
    							System.out.println(getUserNo()+" USER");
    							if(getStatus().equals("Connected"))
    							{
    								int num1 = din.readInt();
    								int num2 = din.readInt();
    								String qnTxt = "What is the sum of " + num1 + " and " + num2;
    								System.out.println(qnTxt);
    							    statusTxtField.setText(qnTxt);
    							    ansBtn.setEnabled(true);
    							    ansTxtField.setEditable(true);
    							}
    							if (getStatus().equals("Submitted"))
    							{
    								String status = ""; 
    								status = din.readUTF();
    								statusTxtField.setText(status+"\nPress play to start the game again");
    								playBtn.setEnabled(true);
    							    ansTxtField.setEditable(false);
    							    submitted = false;
    					        	ansBtn.setEnabled(false);
    					        	setStatus("Initiated");
    							    endThread = true;
    							    setSessionId(0);
    							    setUserNo(0);
    							    din.close();
    							    dout.close();
    							    input.close();
    							    output.close();
    							    s.close();
    							}
    						}
    			        }
    					catch (Exception e) 
    					{
    						e.printStackTrace();
    			        }
    				}
    			}
    		}.start();
    Below is my server thread, there is another java program called Q3Server that runs this thread non-stop and listening to port 12345. Q3Server has a static vector users that have a socket connection with the server and a static integer totalThread that stores the number of user that has a socket connection with the server. There is also a static vector conResetUsers that adds all the users that thrown exception during the socket connections.
    Java Code:
        private synchronized void stateTransition()
        {
        	try
        	{
                output=socket.getOutputStream();
                input=socket.getInputStream();
                din = new DataInputStream(input);
                if(din.available()>0)
                {
                dout = new DataOutputStream(output);
        		String state = din.readUTF();	
        		System.out.println(state+" sdf");
        		if (state.equals("Initiated"))
        		{
        			Q3Server.totalThread++;
        			if (Q3Server.totalThread%2 == 0)
        			{
        				sessionId = Q3Server.totalThread/2; 
        				userNo = 1;
        			}
        			else
        			{
        				if (Q3Server.totalThread == 1)
        				{
        					sessionId = 0;
        				}
        				else
        				{
        					double temp = (double)Q3Server.totalThread/2.0;
        					sessionId = (int)temp;
        				}
        				userNo = 2;
        			}
        			thisUser = new User(state,sessionId,userNo);
        			Q3Server.users.add(thisUser);
                    if (checkUser(sessionId,userNo))
                    {
                    	dout.writeUTF("Found");
                    }
                    else
                    {
                    	dout.writeUTF("Wait");
                    }
                    dout.writeInt(sessionId);
                    dout.writeInt(userNo);
        		}
        		else
        		{
        			[COLOR="Red"]thisUser = getCurrUserInList(din.readInt(),din.readInt());[/COLOR]
        			thisUser.setStatus(state);
                    if (state.equals("Wait"))
        			{
                        if (checkUser(thisUser.getSessionId(),thisUser.getUserNo()))
                        {
                        	System.out.println("");
                        	dout.writeUTF("Found");
                        }
                        else
                        {
                        	dout.writeUTF("Wait");
                        }
                        thisUser.setStatus(state);
                        dout.writeInt(thisUser.getSessionId());
                        dout.writeInt(thisUser.getUserNo());
                        replaceUser(thisUser);                    
        			}
        			else 
        			{
                        if (checkUser(thisUser.getSessionId(),thisUser.getUserNo())== false)
                        {
                        	removeUser(thisUser.getSessionId(),thisUser.getUserNo());
                        	setEndThread(true);
                        }
                        else 
                        {
                        	System.out.println(state+" CHECK!! "+checkOpponentLeft(thisUser));
    	                   	if (checkOpponentLeft(thisUser))
    	                    {
    	                   		delOppFrmReset(thisUser);
                				deleteBothUser(thisUser.getSessionId());
    	                    	dout.writeUTF("Left");
    	                    	setEndThread(true);
    	                    }
    	                    else
    	                    {
    		        			dout.writeUTF(state);
    		                    dout.writeInt(thisUser.getSessionId());
    		                    dout.writeInt(thisUser.getUserNo());
    		                	User otherUser = getTheOtherUser(thisUser.getSessionId(),thisUser.getUserNo());
    		                	if (state.equals("Connected"))
    			    			{
    		                    	if (otherUser.getQuestionSet())
    		                    	{
    		                    		num1 = otherUser.getNum1();
    		                    		num2 = otherUser.getNum2();
    		                    	}
    		                    	else
    		                    	{
    		                    		if (thisUser.getQuestionSet())
    		                    		{
    		                    			num1 = thisUser.getNum1();
    		                    			num2 = thisUser.getNum2();
    		                    		}
    		                    		else
    		                    		{
    		                    			num1 = rand.nextInt(100);
    		                    			num2 = rand.nextInt(100);
    		                    		}
    		                    	}
    		                    	thisUser.setStatus(state);
    		                    	thisUser.setQuestionSet(true);
    		                    	thisUser.setNum1(num1);
    		                    	thisUser.setNum2(num2);
    		                    	replaceUser(thisUser);
    		                		dout.writeInt(num1);
    		                		dout.writeInt(num2);  
    			    			}
    		                    else 
    		                    {
    		                    	int userAns = din.readInt();
    		                    	System.out.println("User answer: "+userAns);
    		                    	String reply = "";
    		                    	thisUser.setAnswerGiven(true);
    		                    	if (otherUser.getAnsGiven())
    		                    	{	
    		                    		if (otherUser.getWinner())
    		                    		{
    		                    			if (userAns!=thisUser.getAnswer())
    		                    			{
    		                    				reply = "Incorrect Answer The answer should be "+thisUser.getAnswer()+".";
    		        	        				replaceUser(thisUser);
    		                    			}
    		                    			else
    		                    			{
    		                    				reply = "Your answer is correct, but the other player have given it earlier.";
    		        	        				replaceUser(thisUser);
    		                    			}
    		                    		}
    		                    		else
    		                    		{
    		                    			if (userAns!=thisUser.getAnswer())
    		                    			{
    		                    				reply = "Incorrect Answer The answer should be "+thisUser.getAnswer()+".";
    		                    				replaceUser(thisUser);
    		                    			}
    		                    			else
    		                    			{
    		                    				reply = "You have won the game"; 
    		                    				thisUser.setWinner(true);
    		        	        				replaceUser(thisUser);
    		                    			}
    		                    		}
    		            				deleteBothUser(thisUser.getSessionId());
    		                    	}
    		                    	else
    		                    	{
    		                			if (userAns!=thisUser.getAnswer())
    		                			{
    		                				reply = "Incorrect Answer The answer should be "+thisUser.getAnswer()+".";
    		    	        				replaceUser(thisUser);
    		                			}
    		                			else
    		                			{
    		                				reply = "You have won the game";
    		                				thisUser.setWinner(true);
    		    	        				replaceUser(thisUser);
    		                			}               		
    		                    	}
    		                		dout.writeUTF(reply);  
    		                		setEndThread(true);	
    		                    }
    	                    }
                       }  
        			}
        		}
                }
        	}
        	catch(Exception e)
        	{
            	System.out.println(thisUser.getSessionId()+" LEFT "+ thisUser.getUserNo()+"\n");
            	System.out.println(thisUser.getStatus());
            	String state = thisUser.getStatus();
            	if (!(state.equals("Initiate")||state.equals("Wait")))
            	{
            		Q3Server.conResetUsers.add(thisUser);
            	}
        		e.printStackTrace();
        	}
        }
    Is my explanation and code SSCCE you wanted to use. The problem is that the request and response between client and server is a nested if statement. I have tried my best. For the full code, I have actually post it in another forum: Threads and I/O stream (I/O and Streams forum at JavaRanch) . The problem is that it will work fine when you run 2 client and the server together to play the game. But when you press the play button the second time, after they have found each other, EOFException will be caught and it occured as hightlighted in red.

Similar Threads

  1. Difference between Thread.yield() and Thread.sleep() methods
    By Nageswara Rao Mothukuri in forum New To Java
    Replies: 12
    Last Post: 07-30-2010, 05:37 PM
  2. how to reduce the thread sleep time and wake up the thread
    By baktha.thalapathy in forum Threads and Synchronization
    Replies: 2
    Last Post: 06-24-2010, 07:36 PM
  3. Trigger main thread method from secondary thread?
    By DigitalMan in forum Threads and Synchronization
    Replies: 8
    Last Post: 01-26-2010, 02:13 AM
  4. Replies: 0
    Last Post: 01-28-2008, 07:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •