CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Nov 2010
    Posts
    15

    Help: Issue while trying to use sockets

    Hi,
    I'm working on a chat client, and not sure if I'm going about the socket connection right. I've been testing it on a POP account to see if my talker class works correctly, but after getting first response, I try to issue my username, then recieve response and it freezes. Any idea?

    Also, Any other tips appreciated.
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    import java.util.*;
    
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    public class Chatter
    {
    	public static void main(String args[])
    	{
    		JFrame	f;
    		f=new ChatterFrame();
    		f.setVisible(true);
    	}
    }
    //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    class ChatterFrame extends JFrame implements ActionListener
    {
    
    Talker myTalker;
    	JPanel		mainPanel;
    	Container	cp;
    	JButton		button;
    	JTextField	inputPort;
    	JTextField 	inputDomain;
    	JLabel		domainLabel;
    	JLabel		portLabel;
    	JLabel		blankLabel;
    
    ChatterFrame()
    {
    setupMainFrame();
    }
    void setupMainFrame()
    {
    	inputDomain=new JTextField("pop.gmx.com");
    	domainLabel=new JLabel("Domain Name:");
    	inputPort=new JTextField("110");
    	portLabel=new JLabel("Port Number: ");
    	button = new JButton("Connect");
    	button.setActionCommand("CONNECT");
    	button.addActionListener(this);
    	blankLabel=new JLabel("");
    
    
    	mainPanel=new JPanel(new GridLayout(3,2));
    	mainPanel.add(domainLabel);
    	mainPanel.add(inputDomain);
    	mainPanel.add(portLabel);
    	mainPanel.add(inputPort);
    	mainPanel.add(blankLabel);
    	mainPanel.add(button);
    
    	cp=getContentPane();
    	cp.add(mainPanel);
    
    	    Toolkit tk;
    	    Dimension   d;
    
    	    tk = Toolkit.getDefaultToolkit();
    	    d = tk.getScreenSize();
    	    setSize(d.width/5, d.height/5);
    	    setLocation(d.width/5,d.height/5);
    
    	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    setTitle("Project #3 - Set Host and Port #");
       		setVisible(true);
    }
    void chatterWindow()
    {
    
    	JFrame	cwF;
    	JPanel	chatPanel;
    	JTextArea chatArea;
    	JTextField sendTF;
    	JButton		msgButton;
    	JButton		exitButton;
    	Container cpc;
    
    
    	cwF=new ChatterFrame();
    	cwF.setVisible(true);
    
    	chatArea=new JTextArea("Chat Project"+"\n",100,100);
    	sendTF=new JTextField("Enter Text Here...");
    	msgButton=new JButton("Sned Msg");
    	exitButton=new JButton("I Quit!");
    
    		chatPanel=new JPanel(new GridLayout(2,2));
    		chatPanel.add(chatArea);
    		chatPanel.add(msgButton);
    		chatPanel.add(sendTF);
    		chatPanel.add(exitButton);
    
    		cpc=getContentPane();
    		cpc.add(mainPanel);
    
    		  Toolkit tk1;
    		  Dimension   d1;
    
    			    tk1 = Toolkit.getDefaultToolkit();
    			    d1 = tk1.getScreenSize();
    			    cwF.setSize(d1.width/5, d1.height/5);
    			    cwF.setLocation(d1.width/5,d1.height/5);
    
    			    cwF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			    cwF.setTitle("Project #3 - Chat Window");
    		   		cwF.setVisible(true);
    				cwF.repaint();
    
    
    
    }
    public void actionPerformed(ActionEvent e)
    {
    	if(e.getActionCommand().equals("CONNECT"));
    	{
    		try
    		{
    		String domainString=inputDomain.getText();
    		int	portInt=Integer.parseInt(inputPort.getText());
    
    		myTalker= new Talker(domainString,portInt);
    		myTalker.recieve();
    		myTalker.send("USER someUserName");
    	//	myTalker.recieve();
    		myTalker.quitFool();
    	//	chatterWindow();
    		}
    		catch(Exception eee)
    		{
    			eee.printStackTrace();
    		}
    	}
    }
    }
    Code:
    import java.util.Vector;
    import java.lang.Object;
    import java.net.*;
    import java.io.*;
    
    public class Talker
    {
    public String domainPath;
    public String domain;
    public int port;
    public int portNumber;
    public String myStr;
    private Socket mySocket;
    private BufferedReader myReader;
    private DataOutputStream out;
    
    
    
     	public static void main(String args[])
    	{
    	}
        public Talker()
        {
    		domainPath="";
    		portNumber=0;
        }
        public Talker(String domain,int port)
     	{
     	    domainPath=domain;
     	    portNumber=port;
     	    System.out.println("Domain Path: "+domainPath+"- Port #: "+portNumber);
    
    
    		try
    		{
    		mySocket=new Socket(domainPath,portNumber);
    		out = new DataOutputStream(mySocket.getOutputStream());
    		myReader = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
    		}
    		catch(UnknownHostException e)
    		{
    		      System.err.println("Unknown Host:"+ domainPath);
    		      System.exit(1);
            }
    		catch(IOException e)
    		{
    			e.printStackTrace();
    
    		}
    
     	}
     	public void send(String myStr)
     	{
    		try
    		{
    		out.writeUTF(myStr+"\n");
    		System.out.println(myStr+"\n");
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    
    		}
    	}
    	public void recieve()
    	{
    		System.out.println("Recieving...");
    		try
    		{
    		String userInput;
    
    		userInput = myReader.readLine();
    		System.out.println("echo: " + userInput);
    
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    
    
    	}
    	public void quitFool()
    	{
    		try
    		{
    		System.out.println("Quiting...");
    		out.close();
    		myReader.close();
    		mySocket.close();
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    	public String toString()
    	{
     	    return domainPath+", "+portNumber;
    	}
    
    }

  2. #2
    Join Date
    Nov 2010
    Posts
    15

    Re: Help: Issue while trying to use sockets

    I need to restate that, When I try the second Talker.recieve() in the actionperformed I get the System.out "Recieving"...then freezes up window and have to exit program.

  3. #3
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Help: Issue while trying to use sockets

    That's presumably because the server isn't sending any data to your Talker client. The readLine() method waits until it receives a line of data before returning, if it doesn't receive any data then it will wait forever and because you are calling it on the event thread your GUI hangs as well.

    You should never call a method that blocks from the event thread, always use a background thread. Try looking at the API docs for javax.swing.SwingWorker
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  4. #4
    Join Date
    Nov 2010
    Posts
    15

    Re: Help: Issue while trying to use sockets

    Hi, Thanks for the suggestion. I looked at a few examples, and not sure If I understand how I need to go about this. Would I go to my talker class, and insert something along the lines of this.

    Then to get that information would I need to do something along the lines of swingworker.execute in my recieve() statement?
    Code:
    @Override
         public String doInBackground() {
              while (! enough && ! isCancelled()) {
    
                          	try
    		{
    		String userInput;
    
    		userInput = myReader.readLine();
    		System.out.println("echo: " + userInput);
    
    		}
    		catch(IOException e)
    		{
    			e.printStackTrace();
    		}
                 }
             }
             return userInput;
    }
         }
    
         @Override
         protected void process(String userInput) {
            System.out.println("Echo: " + userInput);
         }

  5. #5
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Help: Issue while trying to use sockets

    No, your doInBackground() method which executes on the background thread has to call publish(userInput) after it has read a new line of data. The value you pass to publish will be passed on to the process(..) method on the event thread.

    Note there may be a delay between the publishing data and processing that data as two different threads are involved. It may even be the case that several publish calls happen before any process calls are made. This is one of the reasons the process method's parameter is a List of your generic type, it may receive several updates in one go ie all the publish results are queued into a list and when the event thread is ready to run that list is passed to the process method.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured