14 Replies - 1386 Views - Last Post: 10 March 2012 - 05:04 PM Rate Topic: -----

#1 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Peer to Peer chat in single application error?

Posted 29 November 2011 - 04:07 PM

Hey im trying to write a peer to peer chat program based loosely on IRC or similar things. Peer a sends a line peer b sees it and vice versa. However i can get two different computers to connect to eachother but when one tries to send a message a null pointer error shows up:
Exception in thread "main" java.lang.NullPointerException
	at com.perihelionds.text2peer.Text2Peer.acceptMsg(Text2Peer.java:42)
	at com.perihelionds.text2peer.Text2Peer.setListener(Text2Peer.java:34)
	at com.perihelionds.text2peer.Text2Peer.main(Text2Peer.java:26)


I've spent many hours trying to get it work and am at a loss for ideas. Below are the relevant methods.
public static void main(String[] args) throws Exception {
		java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
              g = new GUI();
              g.setVisible(true);
            }
        });
		setListener();
		
	}
	public static void setListener() throws IOException
	{
		ServerSocket welcomeSocket = new ServerSocket(5678);
		while(true){
		Socket handlerSocket = welcomeSocket.accept();
		acceptMsg(handlerSocket);
		}
	}
	public static void acceptMsg(Socket s) throws IOException {
		InputStream inFromClient = s.getInputStream();
		InputStreamReader inReader = new InputStreamReader(inFromClient);
		BufferedReader reader = new BufferedReader(inReader);
		String line = reader.readLine();
		newLine.setText(line); //Here is where the error points to
		g.setMainChat(newLine);
	}



Is This A Good Question/Topic? 0
  • +

Replies To: Peer to Peer chat in single application error?

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2813
  • View blog
  • Posts: 11,907
  • Joined: 20-September 08

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 04:31 PM

Either 'line' or (more likely) 'newLine' is null

This post has been edited by g00se: 29 November 2011 - 04:31 PM

Was This Post Helpful? 1
  • +
  • -

#3 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 05:42 PM

>.<
I forgot to initialize newLine....
however now there are no errors and the lines still dont transfer...Went through my code alot more still not seeing it. so far as i can follow it should be working.
Heres the relevant code
public class Text2Peer {
	
	public Socket handlerSocket = null;
	private static GUI g;
	private static JTextArea newLine = new JTextArea();
	
	public static void main(String[] args) throws Exception {
		java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
              g = new GUI();
              g.setVisible(true);
            }
        });
		setListener();
		
	}
	public static void setListener() throws IOException
	{
		ServerSocket welcomeSocket = new ServerSocket(5678);
		while(true){
		Socket handlerSocket = welcomeSocket.accept();
		acceptMsg(handlerSocket);
		}
	}
	public static void acceptMsg(Socket s) throws IOException {
		
		InputStream inFromClient = s.getInputStream();
		InputStreamReader inReader = new InputStreamReader(inFromClient);
		BufferedReader reader = new BufferedReader(inReader);
		String line = reader.readLine();
		newLine.setText(line);
		g.setMainTxt(newLine);
	}

}


And heres the setMainTxt method from GUI
	public void setMainTxt(JTextArea m)
	{
		this.mainChat.setText(this.mainChat.getText() + m.getText());
	}



For the actual sending im just doing the following
getMainChat().setText(getMainChat().getText() + "\n [" + handleField.getText() + "]: " + textField.getText());
					try {
						outToServer = socket.getOutputStream();
						out = new PrintStream(outToServer, true);
						out.println("\n [" + handleField.getText() + "]: " + textField.getText());
						textField.setText("");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						
						textField.setText("");
						getMainChat().setText(getMainChat().getText() + "\n Error not Connected!");
						e.printStackTrace();
					}


Was This Post Helpful? 0
  • +
  • -

#4 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 06:14 PM

using some strategically placed system.out.printlns ive found that it is indeed transmitting some data but line is null and so shows up as empty.

View Postsnakeman2058, on 29 November 2011 - 06:11 PM, said:

using some strategically placed system.out.printlns ive found that it is indeed transmitting some data but line is null and so shows up as empty.

Cant find the edit button...So i also found out that im not getting a pesistent connection and that no data after the first line is received as the println code is only activated once unless i hit connect between all transmissions. Should i just post all of my code?
heres the connect method:
try {
					socket = new Socket(ipField.getText(), 5678);
					getMainChat().setText(getMainChat().getText() + "\n Connected to Server");
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					mainChat.setText(getMainChat().getText() + " \n Invalid IP address.");
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					mainChat.setText(getMainChat().getText() + " \n Peer unavaliable. Double check they are running Text2Peer and you have the IP correct.");
					e.printStackTrace();
				}


Was This Post Helpful? 0
  • +
  • -

#5 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 06:58 PM

Should i only be using one socket? Because at the moment i have a socket that is initiated under the connect button and a separate socket that accepts the connection.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 09:39 PM

You have a ServerSocket and a Socket, you need both

You have to much static variables/methods in your code it is a very bad approach and defeat all the purpose of having an OO language like Java

Have a class Server, a class Gui, a class Client

The only static method should me main() in the GUI class
There should not be any static variable
It should create a Server object and pass it as parameter to the GUI class

Start by making your Client and Server work in console mode
Then, when it will work, add the GUI
Was This Post Helpful? 1
  • +
  • -

#7 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 10:42 PM

Ok i did as you suggested and it feels alot nicer now. I can get it to say that it connected and recived a connection. however when i try to send a message im getting a null pointer error in my client class shown below.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at com.perihelionds.text2peer.Client.sendMsg(Client.java:44)
	at com.perihelionds.text2peer.GUI$4.actionPerformed(GUI.java:136)
	at javax.swing.JTextField.fireActionPerformed(Unknown Source)
	at javax.swing.JTextField.postActionEvent(Unknown Source)
	at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
	at javax.swing.SwingUtilities.notifyAction(Unknown Source)
	at javax.swing.JComponent.processKeyBinding(Unknown Source)
	at javax.swing.JComponent.processKeyBindings(Unknown Source)
	at javax.swing.JComponent.processKeyEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
	at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
	at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
	at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
	at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)



Heres the client class:
package com.perihelionds.text2peer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	
	private Socket socket;


	public void connect(String ip)
	{
		try {
			socket = new Socket(ip, 5678);
		} catch (UnknownHostException e) {

			System.out.println(" \n Invalid IP address.");
			e.printStackTrace();
		} catch (IOException e) {

			System.out.println(" \n Peer unavaliable. Double check they are running Text2Peer and you have the IP correct.");
			e.printStackTrace();
		}
		System.out.println("Connected to Server");
	}
	
	public void disconnect()
	{
		try {
			socket.close();
		} catch (IOException e) {
			System.out.println("Could not disconnect!!");
			e.printStackTrace();
		}
	}
	
	public void sendMsg(String s)
	{
		
		try {
			OutputStream outToServer = socket.getOutputStream(); //Issue line
			PrintStream out = new PrintStream(outToServer, true);
			out.println(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}


Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Peer to Peer chat in single application error?

Posted 29 November 2011 - 10:52 PM

Your Client class does not have a main() method
Show us the code that:
- creates a Client object
- calls its connect() method
- calls its sendMsg() method

Actually your

OutputStream outToServer;
PrintStream out;

should be in the instance variables of your Client class

the
outToServer = new PrintStream(outToServer, true);
out = socket.getOutputStream(); //Issue line

should be in your connect() method

You do not want to create another instance of these everytime you send a message
Just create them once at connect time
Was This Post Helpful? 1
  • +
  • -

#9 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 30 November 2011 - 09:48 AM

So I did everything that you suggested and it removed the null error thank you. The only thing i didn't do was add main method to client as im unsure what would go in there and you said the only main should be in GUI. however im still not receiving the messages. The line that says something was received is activated but the contents is empty. So no actual message is received. Ive decided to just go for bust and paste all three classes because im completely lost and if i spend any more time on it this morning my head might explode :P Thank you for all the help you've given me so far and im sorry i keep needing it.
GUI.java
package com.perihelionds.text2peer;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;

public class GUI extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2900045523571024631L;
	
	
	private JPanel contentPane;
	private JTextField handleField;
	private JTextField ipField;
	private JTextField textField;
	public JTextArea mainChat;
	private Client client = new Client();

	

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GUI frame = new GUI();					
					frame.setVisible(true);
					new Server();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public GUI() {
		setTitle("Text2Peer");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 646, 433);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		
		JLabel lblHandle = new JLabel("Handle:");
		lblHandle.setFont(new Font("Tahoma", Font.PLAIN, 15));
		panel.add(lblHandle);
		
		handleField = new JTextField();
		panel.add(handleField);
		handleField.setColumns(10);
		handleField.setText("Anon");
		
		JLabel lblIpOfPeer = new JLabel("IP of Peer:");
		lblIpOfPeer.setFont(new Font("Tahoma", Font.PLAIN, 15));
		panel.add(lblIpOfPeer);
		
		ipField = new JTextField();
		panel.add(ipField);
		ipField.setColumns(10);
		ipField.setText("localhost");
		
		JButton btnConnect = new JButton("Connect");
		btnConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt){
					client.connect(ipField.getText());	
			}
		});
		panel.add(btnConnect);
		
		JButton btnDisconnect = new JButton("Disconnect");
		btnDisconnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				client.disconnect();
				System.out.println("Disconnected");
			}
		});
		panel.add(btnDisconnect);
		
		JPanel panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		setMainChat(new JTextArea());
		getMainChat().setText("*****************************************************\r\nText2Peer - A direct way to communicate\r\nFor full instructions please see README.TXT\r\n\r\n*****************************************************");
		getMainChat().setEditable(false);
		scrollPane.setViewportView(getMainChat());
		
		JPanel panel_2 = new JPanel();
		contentPane.add(panel_2, BorderLayout.SOUTH);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		textField = new JTextField();
		textField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String line="\n [" + handleField.getText() + "]: " + textField.getText();
				System.out.println(line);
				client.sendMsg(line);
				textField.setText("");		
			}
		});
		textField.setToolTipText("Enter a line here then push submit");
		textField.setColumns(10);
		panel_2.add(textField);
		
		JButton Submit = new JButton("Submit");
		Submit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String line=" [" + handleField.getText() + "]: " + textField.getText() + "\n";
				System.out.println(line);
				client.sendMsg(line);
				textField.setText("");
			}
		});
		panel_2.add(Submit, BorderLayout.EAST);
	}

	public void setMainChat(JTextArea mainChat) {
		this.mainChat = mainChat;
	}
	public void setMainTxt(JTextArea m)
	{
		System.out.println("setMainTxt called with: " + m.getText());
		this.mainChat.setText(this.mainChat.getText() + m.getText());
	}
	public JTextArea getMainChat() {
		return mainChat;
	}
	
	
}


Server.java
package com.perihelionds.text2peer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread{
	
	private ServerSocket welcomeSocket;
	private Socket handlerSocket = null;
	private String line = "";
	
	Server() {
	      // Create a new, second thread
	      super("Demo Thread");
	      start(); // Start the thread
	   }
	public void run() {
		
		try {
			welcomeSocket = new ServerSocket(5678);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Server Running ...");
		while(true){
		
		try {
			handlerSocket = welcomeSocket.accept();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Connection accepted ...");
		
		
		InputStream inFromClient;
		try {
			inFromClient = handlerSocket.getInputStream();
			InputStreamReader inReader = new InputStreamReader(inFromClient);
			BufferedReader reader = new BufferedReader(inReader);
			line = reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		System.out.println("Read from client: " + line);
		
		}
	}
}


Client.java
package com.perihelionds.text2peer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	
	private Socket socket;
	private OutputStream outToServer;
	private PrintStream out;


	public void connect(String ip)
	{
		try {
			socket = new Socket(ip, 5678);
			outToServer = socket.getOutputStream();
			out = new PrintStream(outToServer, true);
		} catch (UnknownHostException e) {

			System.out.println(" \n Invalid IP address.");
			e.printStackTrace();
		} catch (IOException e) {

			System.out.println(" \n Peer unavaliable. Double check they are running Text2Peer and you have the IP correct.");
			e.printStackTrace();
		}
		System.out.println("Connected to Server");
	}
	
	public void disconnect()
	{
		try {
			socket.close();
		} catch (IOException e) {
			System.out.println("Could not disconnect!!");
			e.printStackTrace();
		}
	}
	
	public void sendMsg(String s)
	{		
		out.println(s);	
	}
}



And thank you by the way
Was This Post Helpful? 0
  • +
  • -

#10 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 30 November 2011 - 10:14 AM

oh and heres the output
Server Running ...
Connection accepted ...
Connected to Server

 [Anon]: yo
Read from client: 


Was This Post Helpful? 0
  • +
  • -

#11 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 30 November 2011 - 11:06 AM

got it! after a bit more searching i realized i never actually parsed the data. so i threw in a scanner and delimiters and it works! now i just need to figure out how to omit the delimiter char lol
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Peer to Peer chat in single application error?

Posted 30 November 2011 - 12:40 PM

You can have a main() per .java file

So the Client class should have

public static void main(String[] args) {
   Client c = new Client();
   c.connect("whatever IP");
}



Now is your GUI for the Server or the Client or both. For both it is a little bit more complicated but feasible and this is what I would do but it is easier to have a ClientGUI and a ServerGUI.
Was This Post Helpful? 1
  • +
  • -

#13 snakeman2058  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-November 11

Re: Peer to Peer chat in single application error?

Posted 30 November 2011 - 01:58 PM

It was for both and i got it working to my satisfaction thanks for all you help!
It probably not the most efficient or cleanest code but it works
Was This Post Helpful? 0
  • +
  • -

#14 Meeemz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-March 12

Re: Peer to Peer chat in single application error?

Posted 10 March 2012 - 12:03 PM

hey I am new to this forum and I really found some interesting topics.
Anyway, I noticed that you did peer-to-peer chatting in one application and I kindda need something similar as piece of my project. would you mind explaining how you fixed the issue with posting what the client says to the main chat area?
Was This Post Helpful? 0
  • +
  • -

#15 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Peer to Peer chat in single application error?

Posted 10 March 2012 - 05:04 PM

This post is more than 3 months old
Meeemz Please do not do necroposting :)
If you do not find your answer here, open a new Thread
P.S. and please do not reply to that post
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1