So my server sends information and receives information. I know this because i tested it on the local host. The problem is that the portion it receives comes out with little squares after the user input.
Here is a picture of the problem.

http://img706.imageshack.us/img706/3342/outputc.jpg
http://yfrog.com/jmoutputcj

Thank You


Server Code:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import javax.swing.*;


public class UDPServer extends JPanel implements ActionListener {
	protected JTextField textField;
	protected JTextArea textArea;
	private final static String newline = "\n";


	String ClientInput = null;
	static String Portnum=null;
	String ServerInput=null;
	static String host=null;
	static String portnum=null;
	static BufferedReader In=null;
	static PrintWriter Out=null;
	static DatagramSocket skt;
	static InetAddress i;
	static int portnumber;
	
	public UDPServer() {
		super(new GridBagLayout());	

		textField = new JTextField(20);
		textField.addActionListener(this);

		textArea = new JTextArea(5, 20);
		textArea.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(textArea);

		//Add Components to this panel.
		GridBagConstraints c = new GridBagConstraints();
		c.gridwidth = GridBagConstraints.REMAINDER;

		c.fill = GridBagConstraints.HORIZONTAL;
		add(textField, c);

		c.fill = GridBagConstraints.BOTH;
		c.weightx = 1.0;
		c.weighty = 1.0;
		add(scrollPane, c);
	}

	public void actionPerformed(ActionEvent evt){
		try {
			IO();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	public void IO() throws IOException{
	    String text = textField.getText();
	   
	    byte[] outbuf = new byte[1024];
	    int len = 1024;
	    byte message[] = text.getBytes();
	    
	    
	    DatagramPacket packet= new DatagramPacket(message, message.length,i /*skt.getInetAddress()*/, portnumber);
	    DatagramPacket packet2 = new DatagramPacket(outbuf, len);
				
		textField.selectAll();			
		textArea.append("Server: "+text + newline);
		skt.send(packet);
		
		skt.receive(packet2);
		String recmessage = new String(packet2.getData());	
		textArea.append("Client: "+recmessage + newline);
		textArea.setCaretPosition(textArea.getDocument().getLength());
	}



	private static void createAndShowGUI() {
		//Create and set up the window.
		JFrame frame = new JFrame("Chat Program Server");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Add contents to the window.
		frame.add(new UDPServer());

		//Display the window.
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) throws UnknownHostException, IOException {

		i = InetAddress.getLocalHost();

		JOptionPane.showMessageDialog(null,"Your Ip Address is: "+i.getHostAddress()+
		"\n Give this to the Client.");
		Portnum=JOptionPane.showInputDialog("What port would you like to use?(4 Digits. Ex:4568)\n" +
		"Tell this to the client.");
		portnumber=Integer.parseInt(Portnum);	
		
		skt =new DatagramSocket(portnumber);
		//ServerSocket serverSocket = new ServerSocket(portnumber);
		//Socket skt =serverSocket.accept();		

		//In=new BufferedReader(new InputStreamReader(skt.getInputStream()));
		//Out=new PrintWriter(skt.getOutputStream(),true);

		createAndShowGUI();
	}
}

Recommended Answers

All 48 Replies

Little squares means you are picking up uninitialized bytes that have the binary value of 0. Check the code to see that you are not going past the end of the good data.

Also put your code in the code tags. Last icon on the right above input window.

I think it might be an error in IO method, since that is were i have byte data, but i don't know what the error might be.

What String are you displaying that has the square boxes? Where do you build that String?

skt.receive(packet2);
String recmessage = new String(packet2.getData());

It recieves the byte's from DatagramPAcket. Then i convert it to a string but it still shows the slots in the array that equal 0;

Lets say byte[] outbuf=new byte[20]; , the program only prints 20 characters(Out of all the clients intput).
Basically,the user has 20 character slots he can use. If he uses less than 20 ,the other slots show as squares. Anything he types after 20 doesn't print.

This is what i want to fix.


Heres a new picture i took:

http://yfrog.com/5soutput2j
http://img208.imageshack.us/img208/7049/output2.jpg

Read the API doc for the skt class.
You are assuming the buffer is full. There are methods that will tell you how many bytes were received. Use that length with the String constructor.

How would i use these two together?

I'm assuming you're a programmer.
The datapacket has some data in a byte buffer. The length of the data is available to you by calling a method for the datapacket.
There is a String constructor that takes a byte array with indexes into that array telling it which bytes to convert to a String.

I've taken 2 high school classes on java. I'm still trying to learn, but i don't understand what your saying.

How do i get rid of the indexes that equal 0?

I was thinking maybe using reaplaceAll(), but i don't think that will work.
I also tried to make a new byte array that only has enough indexes as the words in output. I tried this by using a for loop, then subtracting output.length - count. Coutn would equal the indexes that are 0. This didn't work. I'm stuck!

First you need to read the API doc for the datagram class and for the String class.
Have you done that?
What is the datagram method for getting the length of the bytes received?
What is the String constructor that takes a byte array and some other values that allow you to pick up a section of the bytes in the array?

Vocabulary:

How do i get rid of the indexes that equal 0?

The contents of an array are called elements.
Indexes are used to reference elements in an array.

There are .length, .getlength(),.setlength.
String(byte[] byte)?

String constructor that takes a byte array and some other values that allow you to pick up a section of the bytes in the array?

Here's what I see when I look at the API doc

String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] ascii, int hibyte)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a Charset, charset name, or that use the platform's default charset.
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.
String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] ascii, int hibyte, int offset, int count)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a Charset, charset name, or that use the platform's default charset.
String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.

One of them says: Constructs a new String by decoding the specified subarray of bytes

So you've got the address of an array and the length of the bytes that have data.
Given that can you find a subarray that contains the data?
Hint the subarray starts at location 0.

Ignore this. I wrote something by accident.

This is what i believe you were talking about.

String jack=new String(outbuf,0,outbuf.length);

I still get the same output.

I also tried

String jj=new String(outbuf,0,outbuf.length,"US-ASCII");

I don't know what to do.DX

Why do you use outbuf.length? Is that the number of bytes read into the buffer or the size of the buffer?

What is the datagram method for getting the length of the bytes received?

Wouldn't that be skt.getRecieveBufferSize() ????

or .getlength()

OMG! I got it Thanks to you!!!!
THANK YOU!!! Not only did i get the answer but i learned some new things. Thanks again!

That will happen when you take the time to read the API doc. You're bound to look at more than you need for the current problem. And hopefully some of it sticks.

DAMIT!!! Ok so i ran it on my other computer. Neither of them received any incoming messages. I had done this using TCP,but my problem was that the server/client would only update their respective textArea when they sent a message. Any ideas???

the server/client would only update their respective textArea when they sent a message

Hard to say without seeing code.
What is the code supposed to do? What have you coded to make it do that? Why doesn't it work?
When do you call the setText() or append() methods for the TextArea? If you are using Swing, you need to be careful of updating Swing components on the wrong thread. Swing wants to have it done on its special thread. See the SwingUtilities methods for ways of putting the updating code on the Swing GUI thread.

Well Which should i get to work? The UDP or the other one(which i think is TCP).

UDP:
They're basically the same. The server was able to contact itself on the local host,but when i try to contact another host, nothing shows up and vice-versa.

rver:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;

import javax.swing.*;


public class UDPServer extends JPanel implements ActionListener {
	protected JTextField textField;
	protected JTextArea textArea;
	private final static String newline = "\n";


	String ClientInput = null;
	static String Portnum=null;
	String ServerInput=null;
	static String host=null;
	static String portnum=null;
	static BufferedReader In=null;
	static PrintWriter Out=null;
	static DatagramSocket skt;
	static InetAddress i;
	static int portnumber;

	public UDPServer() {
		super(new GridBagLayout());	

		textField = new JTextField(20);
		textField.addActionListener(this);

		textArea = new JTextArea(5, 20);
		textArea.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(textArea);

		//Add Components to this panel.
		GridBagConstraints c = new GridBagConstraints();
		c.gridwidth = GridBagConstraints.REMAINDER;

		c.fill = GridBagConstraints.HORIZONTAL;
		add(textField, c);

		c.fill = GridBagConstraints.BOTH;
		c.weightx = 1.0;
		c.weighty = 1.0;
		add(scrollPane, c);
	}

	public void actionPerformed(ActionEvent evt){
		try {
			IO();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	public void IO() throws IOException{
		String text = textField.getText();

		byte[] outbuf = new byte[20];
		byte message[] = text.getBytes();


		DatagramPacket packet= new DatagramPacket(message, message.length,skt.getInetAddress(), portnumber);
		DatagramPacket packet2 = new DatagramPacket(outbuf, outbuf.length);

		textField.selectAll();
		textArea.append("Outgoing: "+text + newline);
		skt.send(packet);		
		skt.receive(packet2);				
		String packet2string=new String(outbuf,0,packet2.getLength(),"US-ASCII");

		textArea.append("Incoming: "+packet2string + newline);
		textArea.setCaretPosition(textArea.getDocument().getLength());
	}
	private static void createAndShowGUI() {
		//Create and set up the window.
		JFrame frame = new JFrame("Chat Program Server");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Add contents to the window.
		frame.add(new UDPServer());

		//Display the window.
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) throws UnknownHostException, IOException {

		i = InetAddress.getLocalHost();

		JOptionPane.showMessageDialog(null,"Your Ip Address is: "+i.getHostAddress()+
		"\n Give this to the Client.");
		Portnum=JOptionPane.showInputDialog("What port would you like to use?(4 Digits. Ex:4568)\n" +
		"Tell this to the client.");
		portnumber=Integer.parseInt(Portnum);	

		skt = new DatagramSocket(portnumber);
		//ServerSocket serverSocket = new ServerSocket(portnumber);
		//Socket skt =serverSocket.accept();		

		//In=new BufferedReader(new InputStreamReader(skt.getInputStream()));
		//Out=new PrintWriter(skt.getOutputStream(),true);

		createAndShowGUI();
	}
}

TCP:
The only difference in the TCP one is the sockets.

InetAddress i = InetAddress.getLocalHost();

		JOptionPane.showMessageDialog(null,"Your Ip Address is: "+i.getHostAddress()+
		"\n Give this to the Client.");
		Portnum=JOptionPane.showInputDialog("What port would you like to use?(4 Digits. Ex:4568)\n" +
		"Tell this to the client.");
		int portnumber=Integer.parseInt(Portnum);	

		ServerSocket serverSocket = new ServerSocket(portnumber);
		Socket skt =serverSocket.accept();		

		In=new BufferedReader(new InputStreamReader(skt.getInputStream()));
		Out=new PrintWriter(skt.getOutputStream(),true);


And this is another difference. Other than these 2 things, they're the same.

String text = textField.getText();			
		textArea.append("Server: "+text + newline);
		textField.selectAll();					
		Out.println(text);
		ClientInput=In.readLine();
		textArea.append("Client: "+ClientInput + newline);
		textArea.setCaretPosition(textArea.getDocument().getLength());

Try adding some println() statements to display the text as it is being added to the textarea. Then if you see that the println() shows the data, but the textarea does not show it for a while, there is a GUI output timing problem.

I don't think my sockets connect. Reading the api i think i need to issue the

skt.Connect();

after line 100. Or are the sockets already connected?

I've never used connect(). I have used send() and receive().
I don't know what connected means with the UDP protocol.

If i use just skt.DatagramPacket(4568); Then i use skt.send(packet);, that will work?
Is the socket connected at this point?

Also packet,which is what i'm sending, is defined like this. Is it ok to have "skt.getInetAddress()" in there?

DatagramPacket packet= new DatagramPacket(message,message.length,skt.getInetAddress(), portnumber);

UDP is a connection-less protocol. You address a message and send it. Maybe it'll be delivered.

Ok so they both connect! YAY! Now the problem is that if i'm the server, I tpe something. The client doesn't see it and i can't type anything again until the client sends me somethiing. When the client sends something, then he see's what i wrote, and I (the server), can type something again. It's like the textArea doesn't update itself. I don't know how to fix it.

Oh and the problem before i believe was that i needed to add skt.connect(inetaddress,port); to both server and client. I figured it out after reading some of the api. XD Thanks for all your help!

Work on your logic a bit. Take a piece of paper and make two columns: one for client and one for server. Have one do something and indicate what the other will see and then do.
Consider what happens when a receive()blocks. You may need some threads to allow both sending and receiving concurrently.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.