Sign in to follow this  

[java] TCP/IP client/server error . please help!!!!

This topic is 4588 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

My client/server program has an error: the client sends the information, but the server doesn't do anything that i told it to. it's not multithreaded or NIO, and is extrememly short, so here's the code: CLIENT CODE (guichat.java) : // GUI NOT USED, CMD LINE ONLY. USAGE: java guichat dataToSendToServer import java.net.*; import java.io.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JScrollPane; import javax.swing.JFrame; public class guichat extends JPanel implements ActionListener { protected static BufferedReader in; protected static PrintWriter out; protected static String ip; protected static int port; protected static JTextArea textarea; protected static JTextField textfield; protected static JScrollPane scrollpane; public guichat(String hostip, int hostport) { ip = hostip; port = hostport; } public static void sendString(String data) throws Exception { Socket client = new Socket("127.0.0.1", 5555); StringBuffer drec = new StringBuffer(); in =new BufferedReader( new InputStreamReader( client.getInputStream())); out =new PrintWriter ( client.getOutputStream(),true); out.println(data); String line = null; while ((line = in.readLine()) != null) { drec.append(line + "\n"); } String output = drec.toString(); System.out.println(drec + "\n"); } protected static final class AppCloser extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } public static void main(String args[]) throws Exception { sendString(args[0]); } } // End App SERVER CODE (gcserver.java) : // USAGE: java gcserver // run on a seperate cmd prompt import java.net.*; import java.io.*; public class gcserver { int listenPort; public gcserver(int listPort) { listenPort = listPort; } public void acceptConnections() { try { ServerSocket server = new ServerSocket(listenPort); Socket incomingConnection = null; while (true) { incomingConnection = server.accept(); handleConnection(incomingConnection); } } catch (BindException e) { System.out.println("Unable to bind to port " + listenPort); } catch (IOException e) { System.out.println("Unable to instantiate a ServerSocket on port: " + listenPort); } } public void handleConnection(Socket incomingConnection) { try { OutputStream outputToSocket = incomingConnection.getOutputStream(); InputStream inputFromSocket = incomingConnection.getInputStream(); BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket)); PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream()); String line = null; while ((line = streamReader.readLine()) != null) { streamWriter.println(line); } } catch(Exception exce) { } } public static void main(String args[]) { gcserver server = new gcserver(5555); server.acceptConnections(); System.out.println("Server is up....."); } } ============================================ and that's it. oddly enough, i can't even get the system.out.println() method to work. thanks in advance

Share this post


Link to post
Share on other sites
LoL...

1) Use the source tag. [ source lang="java" ] < your code > [ / source ]
2) Give us more information.. stack trace (in case of any exceptions being thrown), or describe each problem separately.
3) Are you sure that your SDK is properly installed, and the environment properly set up? I ask because you say System.out.println() does not work...

Son Of Cain

Share this post


Link to post
Share on other sites
[ source lang="java" ]

CLIENT CODE (guichat.java) :

// GUI NOT USED, CMD LINE ONLY. USAGE: java guichat dataToSendToServer
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;

public class guichat extends JPanel implements ActionListener {

protected static BufferedReader in;
protected static PrintWriter out;
protected static String ip;
protected static int port;

protected static JTextArea textarea;
protected static JTextField textfield;
protected static JScrollPane scrollpane;

public guichat(String hostip, int hostport) {
ip = hostip;
port = hostport;
}

public static void sendString(String data) throws Exception {

Socket client = new Socket("127.0.0.1", 5555);

StringBuffer drec = new StringBuffer();


in =new BufferedReader( new InputStreamReader( client.getInputStream()));
out =new PrintWriter ( client.getOutputStream(),true);

out.println(data);


String line = null;
while ((line = in.readLine()) != null) {
drec.append(line + "\n");
}
String output = drec.toString();
System.out.println(drec + "\n");

}


protected static final class AppCloser extends WindowAdapter {

public void windowClosing(WindowEvent e) {

System.exit(0);
}

}

public static void main(String args[]) throws Exception {

sendString(args[0]);

}

} // End App

SERVER CODE (gcserver.java) :

// USAGE: java gcserver
// run on a seperate cmd prompt
import java.net.*;
import java.io.*;

public class gcserver {
int listenPort;

public gcserver(int listPort) {
listenPort = listPort;
}

public void acceptConnections() {
try {
ServerSocket server = new ServerSocket(listenPort);
Socket incomingConnection = null;
while (true) {
incomingConnection = server.accept();
handleConnection(incomingConnection);
}
} catch (BindException e) {
System.out.println("Unable to bind to port " + listenPort);
} catch (IOException e) {
System.out.println("Unable to instantiate a ServerSocket on port: " + listenPort);
}
}

public void handleConnection(Socket incomingConnection) {
try {
OutputStream outputToSocket = incomingConnection.getOutputStream();
InputStream inputFromSocket = incomingConnection.getInputStream();

BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket));
PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream());
String line = null;

while ((line = streamReader.readLine()) != null) {
streamWriter.println(line);
}

} catch(Exception exce) { }
}

public static void main(String args[]) {
gcserver server = new gcserver(5555);
server.acceptConnections();
System.out.println("Server is up.....");
}

}
[ / source ]


when it (the client) is running , it's supposed to send data to the server through I/O and once the server recieves it sends data back to client so it can show the output by the System.out.println(), which works btw, and the error is that the server doesn't recieve the information (i tested this) and so the client does nothing. possible errors that i discovered when re-arranging the source: NullPointer Exception. it doesn't show up on this one as an error, however.

Share this post


Link to post
Share on other sites

Hi,

Use the source tag without the spaces before the "[" and "]" chars ;)

Now about the error... NullPointerException is thrown when you trying to call a method for a "null" object, an object that has not been properly initialized by a constructor. Try the following:


try {

// Code that can throw an exception

} catch (Exception ex) {
// Will print the stack trace of this exception
ex.printStackTrace();
}


This method, printStackTrace(), will show you all method calls related to the code you're working with in the "try" block. It returns to you the very line of code where the exception was thrown ;)

BTW, the problem seems to be that your server is not running as a Thread. Usually, we do the following:


public final class GCServer implements Runnable {

public void run() {
// It's here that you accept incoming connections
}

}



Hope this helps,
Son Of Cain

Share this post


Link to post
Share on other sites
woah woah wait. not right. i'm sorry, i wasn't trying to make the server multithreaded yet, and just deleting the Thread thing doesn't cut the cheese...
so erm... anymore suggestions?

edit:
alright. found the problem. i cleaned up the code a bit (erased the constructor for guichat.java and its ActionPerformed event handler. i have a ConnectionException: connection refused.

Share this post


Link to post
Share on other sites
Quote:
Original post by Fender Bender
woah woah wait. not right. i'm sorry, i wasn't trying to make the server multithreaded yet, and just deleting the Thread thing doesn't cut the cheese...
so erm... anymore suggestions?


If you were trying to make a server in C++, I could understand not wanting a bunch of threads running. It can get tought to debug. But with java... it is easy. At least it will give you a way to stop the server.

public class MyServer {

private volatile boolean isRunning = false;
private Server server = null;

public void startServer() {
server = new Server();
isRunning = true;
server.start();
}

public void stopServer() {
isRunning = false;
try {
server.join();
} catch (Exception e) {
e.printStackTrace();
}

server = null;
}

private class Server extends Thread {
public void run() {
while( isRunning ) {
// server stuff here
}
}
}
}


You can at least have a way to stop ther server. Using timeout values for accepting connections. However, keep in mind that using Non-Blocking IO is better, otherwise a server stuck in accept() cannot process messages from anyone else.

Share this post


Link to post
Share on other sites

This topic is 4588 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this