(Link to AcmlmWiki) Offline: thank ||bass
Register | Login
Views: 13,040,846
Main | Memberlist | Active users | Calendar | Chat | Online users
Ranks | FAQ | ACS | Stats | Color Chart | Search | Photo album
06-26-24 01:31 PM
0 users currently in Programming.
Acmlm's Board - I3 Archive - Programming - Java Sockets. New poll | |
Add to favorites | Next newer thread | Next older thread
User Post
Squash Monster

Bouncy


 





Since: 11-18-05
From: Right next to myself.

Last post: 6345 days
Last view: 6339 days
Posted on 01-29-06 07:26 PM Link | Quote
A friend and I are trying to learn how to connect to eachother's computers via Java sockets, and aren't having very much luck.

Every time we try to run, the client side says it timed out, and the server side claims its IP is 0.0.0.0.

Anyone have any ideas what could be going wrong?

(Code follows. Sorry it's all double-spaced -- blame the pre tag. Anyone have a solution for that?)


import java.net.Socket;
import javax.swing.JOptionPane;
import java.net.InetAddress;
import javax.swing.JFrame;
import java.net.UnknownHostException;
import java.io.IOException;

class Client
{
public static void main(String[] args)
{
Socket socket = null;

String input = JOptionPane.showInputDialog("IP Address to connect to?");
try
{
socket = new Socket(input, LearnNetwork.PORT_NUM);
}
catch(UnknownHostException e)
{
System.out.println("Do not know of host: " + e.getMessage());
System.exit(-1);
}
catch(IOException e)
{
System.out.println("IO Exception connecting to host: " + e.getMessage());
System.exit(-1);
}

JFrame appFrame = new JFrame();
LearnNetwork ln = new LearnNetwork(socket);
appFrame.setContentPane(ln);
appFrame.pack();
appFrame.show();
}
}



import java.net.Socket;
import java.net.ServerSocket;
import javax.swing.JFrame;
import java.io.IOException;
import java.net.InetAddress;
import javax.swing.JOptionPane;

class Server
{
public static void main(String[] args)
{
Socket socket = null;

try
{
ServerSocket serverSocket = new ServerSocket(LearnNetwork.PORT_NUM);
System.out.println("Address is: ");
byte[] address = serverSocket.getInetAddress().getAddress();
for(int i = 0; i < address.length; i++)
System.out.print(address + ".");

socket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println("Error connecting to client: " + e.getMessage());
System.exit(-1);
}

JFrame appFrame = new JFrame();
LearnNetwork ln = new LearnNetwork(socket);
appFrame.setContentPane(ln);
appFrame.pack();
appFrame.show();
}
}



import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.Graphics;

class Avatar implements KeyListener
{
private int x;
private int y;
private int xs = 0;
private int ys = 0;

public Avatar(int _x, int _y)
{
x = _x;
y = _y;
}

public void doStep()
{
x += xs;
y += ys;
}

public String getUpdate()
{
return intToString(x) + intToString(y) + intToString(xs) + intToString(ys);
}

public void setUpdate(String update)
{
x = stringToInt(update.substring(0,4));
y = stringToInt(update.substring(4,8));
xs = stringToInt(update.substring(8,12));
ys = stringToInt(update.substring(12,16));
}

private static String intToString(int num)
{
String result = "" + num;
while(result.length() < 4)
{
result = " " + result;
}
return result;
}

private static int stringToInt(String str)
{
while(str.substring(0,1).equals(" "))
{
str = str.substring(1);
}
return Integer.parseInt(str);
}

public void draw(Graphics g)
{
g.fillRect(x, y, 4, 4);
}

public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_RIGHT: xs = 1; break;
case KeyEvent.VK_UP: ys = -1; break;
case KeyEvent.VK_LEFT: xs = -1; break;
case KeyEvent.VK_DOWN: ys = 1; break;
}
}

public void keyReleased(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_RIGHT: if (xs > 0) xs = 0; break;
case KeyEvent.VK_UP: if (ys < 0) ys = 0; break;
case KeyEvent.VK_LEFT: if (xs < 0) xs = 0; break;
case KeyEvent.VK_DOWN: if (ys > 0) ys = 0; break;
}
}

public void keyTyped(KeyEvent e) {}

public static void main(String[] args)
{
//Test run, just tests update logic
String temp = intToString(1) + intToString(-1);
System.out.println(temp);
System.out.println(stringToInt(temp.substring(0,4)));
System.out.println(stringToInt(temp.substring(4,8)));
}
}



import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Dimension;
import java.io.IOException;

class LearnNetwork extends JPanel implements ActionListener
{
public static final int PORT_NUM = 6112;

private Socket socket;
private PrintWriter out;
private BufferedReader in;

private Avatar us = new Avatar(0, 0);
private Avatar them = new Avatar(0, 0);
private Timer t = new Timer(15, this);
private boolean updaterStarted = false;

public LearnNetwork(Socket _socket)
{
socket = _socket;
try
{
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch(IOException e)
{
System.out.println("Error connecting: " + e.getMessage());
System.exit(-1);
}

setPreferredSize(new Dimension(512, 512));
setFocusable(true);
addKeyListener(us);
t.start();
}

public void actionPerformed(ActionEvent eve)
{
us.doStep();
them.doStep();
out.println(us.getUpdate());
repaint();

//Abuse a boolean and the automatic threading of timers to get this fork
if(!updaterStarted)
{
updaterStarted = true;
while(updaterStarted)
{
//Closed from outside by setting updaterStarted back to false
try
{
them.setUpdate(in.readLine());
}
catch(IOException e)
{
System.out.println("Error reading data from connection: " +
e.getMessage());
System.exit(-1);
}
}
}
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
us.draw(g);
them.draw(g);
}
//TODO -- close all input and output streams, close connections
}



(edited by Squash Monster on 01-29-06 06:30 PM)
neotransotaku

Sledge Brother
Liberated from school...until MLK day








Since: 11-17-05
From: In Hearst Field Annex...

Last post: 6340 days
Last view: 6337 days
Posted on 01-30-06 12:08 AM Link | Quote
Say, are you guys on the same network? if you and your friend are behind two NATs, then you two won't be able to see each other. As a result, you need the actual IP address of the connection, plus some port forwarding, to be able to connect properly.

The reason why you see 0.0.0.0 locally is because servers don't care where they are, just only what port number they need to listen to.

Also, it is best not to be listening and connecting with the same port number. So, when you make a client socket, it shouldn't be the same socket as the server.

EDIT: Here is Sun's Socket tutorial if you haven't looked at it yet--but I believe you did the same thing in the tutorial


(edited by neotransotaku on 01-29-06 11:14 PM)
(edited by neotransotaku on 01-29-06 11:15 PM)
Zem
Permabanned. Flaming, trolling, reregistering.


 





Since: 11-18-05

Last post: 6660 days
Last view: 6660 days
Posted on 01-30-06 03:57 AM Link | Quote
The solution for the <pre> issue is to use CSS to have it hide <br> tags inside it. For example, in my profile, I have:
<style type="text/css">pre.nobrpre br { display: none }</style><pre class="nobrpre">blah blah blah</pre>
Squash Monster

Bouncy


 





Since: 11-18-05
From: Right next to myself.

Last post: 6345 days
Last view: 6339 days
Posted on 01-30-06 10:48 AM Link | Quote
We're not on the same network, and we were using IP addresses.

The socket tutorial makes too many assumptions and doesn't work all that well. But yes, I did check my code against it. They're quite similar.

How exactly would you recomend setting it up so they're not listening and connecting the same port number? Would you connect twice, and have each computer use one port to send and the other to receive?
neotransotaku

Sledge Brother
Liberated from school...until MLK day








Since: 11-17-05
From: In Hearst Field Annex...

Last post: 6340 days
Last view: 6337 days
Posted on 01-31-06 05:49 PM Link | Quote
testing your code, everything is okay. You can leave the code intact because I didn't notice difference between SocketServer and Socket. So, SocketServer is in Server class and Socket is in Client class. That's correct.

I believe your problem goes down to IP address problems.

On the computer that will run the server, get the IP address of the server using ipconfig (if you are using windows). If the ip address starts with 192 or 10, you need to get the IP address of the internet connection somehow. The exception to this is if both computers are on the same network. Then you can just stick with the 192 or 10 IP address.

Once you get this IP address, then this is the IP address the client will use when you run the client on another computer.

If you get the IP address not to start with 192 or 10, then the issue now is the server is behind a firewall and you need to poke a hole through the firewall to accept connections on the server's port number.
Squash Monster

Bouncy


 





Since: 11-18-05
From: Right next to myself.

Last post: 6345 days
Last view: 6339 days
Posted on 02-11-06 11:05 AM Link | Quote
Sorry it took so long to get back to this thread.

Eventually we found the problem -- my friend typoed when he set up port forwarding so his router sent requests to connect to the game through the wrong computer .


A new question arises:

Currently, as you may have noticed, we're sending updates as strings and using number formatting functions to get them back together and stuff.

I'm trying to come up with a better way to go about that.

What would be the best way to format data? Make an Update class and send objects of it across through serialization?
neotransotaku

Sledge Brother
Liberated from school...until MLK day








Since: 11-17-05
From: In Hearst Field Annex...

Last post: 6340 days
Last view: 6337 days
Posted on 02-11-06 12:21 PM Link | Quote
It is probably best to send objects that all derived from a base class. On the sender's end, they initialize a "packet" and send that off using an object writer. Then using a series of instanceof checks at the receiver's end, to determine the actual type of the "packet" that is sent so that the data can easily be extracted.
Add to favorites | Next newer thread | Next older thread
Acmlm's Board - I3 Archive - Programming - Java Sockets. |


ABII

Acmlmboard 1.92.999, 9/17/2006
©2000-2006 Acmlm, Emuz, Blades, Xkeeper

Page rendered in 0.043 seconds; used 391.41 kB (max 476.90 kB)