need an advice
hi, i just want to ask someone's advice... i have a test program that works as a chat program... i have Strider.java as the server and Hiryu.java as the client. My question is, why is that the server can't detect any connection.. or the client can't connect to the server while both of them are alreay running?... i can't see if theres a connection between the two really happens...
[b]//Strider.java[/b]
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
publicclass Striderextends JFrameimplements ActionListener
{
ObjectOutputStream output;
ObjectInputStream input;
String msg;
JTextField txtfld;
JTextArea txtarea;
public Strider()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
txtfld =new JTextField(10);
txtarea =new JTextArea(10,20);
txtfld.addActionListener(this);
c.add(txtfld);
c.add(new JScrollPane(txtarea));
setSize(230,250);
show();
}
publicvoid actionPerformed(ActionEvent e)
{
sendData(e.getActionCommand());
}
publicvoid runStrider()
{
ServerSocket server;
Socket connection;
int counter = 1;
try{
server =new ServerSocket(5000, 100);
while(true){
txtarea.setText("Waiting for someone to connect");
connection = server.accept();
txtarea.append("Connection" + counter +"received from:" + connection.getInetAddress().getHostName());
output =new ObjectOutputStream(connection.getOutputStream());
output.flush();
input =new ObjectInputStream(connection.getInputStream());
txtarea.append("\n Got I/O Streams \n");
msg ="Server>> Connection Successful";
output.writeObject(msg);
output.flush();
do{
try{
msg = (String) input.readObject();
txtarea.append("\n" + msg);
txtarea.setCaretPosition(txtarea.getText().length());
}
catch(ClassNotFoundException cnfex){
txtarea.append("\nUnknown Object type received");
}
}while(!msg.equals("Client>> Terminate"));
txtarea.append("\nUser Terminated connection");
output.close();
input.close();
connection.close();
++counter;
}
}
catch(EOFException eof){
System.out.println("Client terminated connection");
}
catch(IOException io){
io.printStackTrace();
}
}
publicvoid sendData(String s)
{
try{
output.writeObject("Server>>" + s);
output.flush();
txtarea.append("\nServer>>" + s);
}
catch(IOException cnfex){
txtarea.append("\nError writing Object");
}
}
publicstaticvoid main(String[] args)
{
Strider app =new Strider();
app.addWindowListener(
new WindowAdapter()
{
publicvoid windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
app.runStrider();
}
}
[b]//Hiryu.java[/b]
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
publicclass Hiryuextends JFrameimplements ActionListener
{
ObjectOutputStream output;
ObjectInputStream input;
String msg;
JTextField txtfld;
JTextArea txtarea;
public Hiryu()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
txtfld =new JTextField(10);
txtarea =new JTextArea(10,20);
txtfld.addActionListener(this);
c.add(txtfld);
c.add(new JScrollPane(txtarea));
setSize(230,250);
show();
}
publicvoid actionPerformed(ActionEvent e)
{
sendData(e.getActionCommand());
}
publicvoid runClient()
{
Socket client;
try{
txtarea.setText("Attempting Connection\n");
client =new Socket(InetAddress.getByName("127.168.2.109"), 5000);
txtarea.append("Connected to:" + client.getInetAddress().getHostName());
output =new ObjectOutputStream(client.getOutputStream());
output.flush();
input =new ObjectInputStream(client.getInputStream());
txtarea.append("\n Got I/O Streams \n");
msg ="Server>> Connection Successful";
output.writeObject(msg);
output.flush();
do{
try{
msg = (String) input.readObject();
txtarea.append("\n" + msg);
txtarea.setCaretPosition(txtarea.getText().length());
}
catch(ClassNotFoundException cnfex){
txtarea.append("\nUnknown Object type received");
}
}while(!msg.equals("Server>> Terminate"));
txtarea.append("\nUser Terminated connection");
output.close();
input.close();
client.close();
//++counter;
}
catch(EOFException eof){
System.out.println("Client terminated connection");
}
catch(IOException io){
io.printStackTrace();
}
}
publicvoid sendData(String s)
{
try{
output.writeObject("Client>>" + s);
output.flush();
txtarea.append("\nClient>>" + s);
}
catch(IOException cnfex){
txtarea.append("\nError writing Object");
}
}
publicstaticvoid main(String[] args)
{
Hiryu app =new Hiryu();
app.addWindowListener(
new WindowAdapter()
{
publicvoid windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
app.runClient();
}
}
Here's one I prepared yesterday... straight out of the sun tut's, except this one compiles and kind of works... Actaully I've been stuffing around with shutting the server down from the client, but I can't figure the non-blocking I/O which would be required to go into an interuptable waiting-for-input state... I did find Apache MINA though I kinda got side tracked....
So, Without any further rambling, digression, or other untoward and unhelpful side trips into MY problems... Here are the fabled codez.
MultiEchoClient
//http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
package tutorials.sun.networking.sockets;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.ConnectException;
public class MultiEchoClient
{
private static final String HOST_NAME = "localhost";
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
Socket socket = null;
PrintWriter sockout = null;
BufferedReader sockin = null;
try {
// create a client socket
socket = new Socket(HOST_NAME, MultiEchoServer.PORT_NUMBER);
// hook the sockets input & output streams
sockout = new PrintWriter(socket.getOutputStream(), true);
sockin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// read & display the servers welcome message
System.out.println(sockin.readLine());
// send whatever the user enters to the server, which echo's it back,
// and we just display it back to the client (reversed)
String message;
while ((message = stdin.readLine()) != null) {
sockout.println(message);
String response = sockin.readLine();
if(response==null) break; //server has died
System.out.println("< " + response);
}
} catch (UnknownHostException e) {
System.err.println(e + " - hostname="+HOST_NAME+", port="+EchoServer.PORT_NUMBER);
} catch (ConnectException e) {
System.err.println(e + " - hostname="+HOST_NAME+", port="+EchoServer.PORT_NUMBER);
} catch (IOException e) {
System.err.println(e);
} finally {
try {if(sockout!=null)sockout.close();} catch (Exception ignore) {}
try {if(sockin!=null)sockin.close();} catch (Exception ignore) {}
try {if(socket!=null)socket.close();} catch (Exception ignore) {}
try {if(stdin!=null)stdin.close();} catch (Exception ignore) {}
}
}
}
MultiEchoServer
//http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
package tutorials.sun.networking.sockets;
/*
cd /d C:\Java\home\src\forums\chat
java -cp c:\java\home\classes tutorials.sun.networking.sockets.MultiEchoClient
*/
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
/**
* handles each requests from a client socket
*/
class SocketHandler extends Thread
{
private static final boolean AUTOFLUSH = true;
private static int id = 1;
private Socket socket = null;
private PrintWriter sockout = null;
private BufferedReader sockin = null;
SocketHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
sockout = new PrintWriter(socket.getOutputStream(), AUTOFLUSH);
sockin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send a greeting message
int myid = id++;
sockout.println("Connected to MultiEchoServer.SocketHandler number="+myid+", threadId="+this.getId());
// now echo requests from the client back to the client.
String request = null;
while ((request = sockin.readLine()) != null) {
System.out.println(myid+"< "+request);
if ("bye".equals(request)) {
break;
}
if ("shutdown".equals(request)) {
MultiEchoServer.shutdown();
break;
}
String response = request;
System.out.println(myid+"> "+response);
sockout.println(response);
}
System.out.println("end of try");
} catch (Exception e) {
System.out.println("exception");
System.err.println(e);
} finally {
System.out.println("finally");
try {if(sockout!=null)sockout.close();} catch (Exception ignore) {}
try {if(sockin!=null)sockin.close();} catch (Exception ignore) {}
try {if(socket!=null)socket.close();} catch (Exception ignore) {}
System.out.println("end of finally");
}
System.out.println("end of run method");
}
}
public class MultiEchoServer
{
public static final int PORT_NUMBER = 4448;
private static volatile boolean listening = true;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter sockout = null;
BufferedReader sockin = null;
// create a "socket factory"
try {
serverSocket = new ServerSocket(PORT_NUMBER);
} catch (IOException e) {
System.err.println(e+" - new ServerSocket("+PORT_NUMBER+") failed.");
System.exit(1);
}
// create a client listener socket for each connect request.
try {
do {
new SocketHandler(serverSocket.accept()).start();
} while(listening);
System.err.println("Shutting down");
} catch (IOException e) {
System.err.println(e+" - serverSocket.accept() failed.");
} finally {
try {if(serverSocket!=null)serverSocket.close();} catch (Exception ignore) {}
}
}
public static void shutdown() {
listening = false;
}
}
Why Sun confused localhost with some ancient greek poofta I'll never know.
Keith.