import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class Client {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private String username = null;
private static String host = "localhost";
private static int port = 2000;
private Client(String host, int port) {
this.host = host;
this.port = port;
}
public boolean start() {
try {
socket = new Socket(host, port);
}
catch (Exception ec) {
System.out.println("Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":"
+ socket.getPort();
System.out.println(msg);
try {
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
System.out.println("Streams created.");
} catch (IOException eIO) {
System.out.println("Exception creating new Input/output Streams: "
+ eIO);
return false;
}
try {
username = JOptionPane.showInputDialog("Enter a username");
out.writeObject(username);
System.out.println(username + " sent to the server.");
} catch (IOException eIO) {
System.out.println("Exception doing login : " + eIO);
return false;
}
return true;
}
public static void main(String[] args) {
Client client = new Client(host, port);
client.start();
}
}
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket sSocket;
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private String username;
private static int port = 2000;
private boolean keepGoing = true;
public void run() {
while (keepGoing) {
try {
sSocket = new ServerSocket(port);
System.out.println("Waiting on connection...");
socket = sSocket.accept();
System.out.println("Connection accepted.");
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException io) {
io.printStackTrace();
}
try {
username = (String) in.readObject();
System.out.println(username);
} catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
}
}
}
public void stop() {
keepGoing = false;
try {
in.close();
out.close();
socket.close();
sSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is what I get as a result:
Client result:
Connection accepted localhost/127.0.0.1:2000
Server result:
Waiting on connection... Connection accepted.
So my question is, why is my client not displaying "Streams created." If the streams aren't created I can not finish executing my code.

New Topic/Question
Reply



MultiQuote




|