Conflicts between JavaFX and Socket - java

I'm trying to set up a Server with a simple GUI where I print when a client make a connection and for its standard operations. The problem happens when I try to execute it, because the GUI doesn't start (even if NetBeans says that the program is executed) and I can't understand if there is a sort of conflict between the threads or if I called it in a wing way. This is the code where the program starts:
public class Server extends Application {
#Override
public void start(Stage stage) throws Exception {
FXMLLoader sLoader = new FXMLLoader(getClass().getResource("server.fxml"));
BorderPane root = new BorderPane(sLoader.load());
ServerController sController = sLoader.getController();
sController.initModel();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
This is the controller of the Server, I put here, in the init function, the part where the Socket waits for the client:
public class ServerController {
#FXML
private TextArea textarea;
public void initModel() {
try {
int i = 1;
ServerSocket s = new ServerSocket(5000);
while (true) {
Socket incoming = s.accept(); // si mette in attesa di richiesta di connessione e la apre
textarea.setText("In attesa di connessioni...");
Runnable r = new ThreadedEchoHandler(incoming, i);
new Thread(r).start();
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ThreadedEchoHandler implements Runnable {
private Socket incoming;
private int counter;
/**
* Constructs a handler.
*
* #param i the incoming socket
* #param c the counter for the handlers (used in prompts)
*/
public ThreadedEchoHandler(Socket in, int c) {
incoming = in;
counter = c;
}
//Con questo gestisco le stringhe
public void run() {
try {
try {
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true);
//out.println("Hello! Enter BYE to exit.");
// echo client input
boolean done = false;
while (!done && in.hasNextLine()) {
String line = in.nextLine();
//out.println("Echo: " + line);
//System.out.println("ECHO: " + line);
if (line.trim().equals("BYE")) {
done = true;
}
}
} finally {
incoming.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Handle Java Socket connection between 2 JFrames

I'm trying to create a client/server application using sockets, I have 2 JFrames (2 seperate classes) , a user will initially open up the one frame and there's a button to go to the other JFrame, when clicked it disposes the previous frame and opens the new frame.
I'd like to know how I could switch back and forth between these 2 JFrames without my program crashing and needing to forcefully close, I am establishing the connection in the constructor of each JFrame.
try {
server = new Socket("localhost", PORT);
// creates & instantiates objectInput and output streams
getStreams();
} catch (IOException ex) {
System.out.println("error creating socket: " + ex.getMessage());
}
I have these in the constructor of both JFrames
EDIT
Server
public class Testserver {
private ServerSocket serverSocket;
private Socket client;
private final int PORT = 5432;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
public Testserver() {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
System.out.println("error creating server socket: " + ex.getMessage());
}
}
private void listenForClient() {
try {
System.out.println("Server is running and is waiting/listening for a connection to be established.");
////JOptionPane.showMessageDialog(null, "Server is running and is waiting/listening for a connection to be established." );
client = serverSocket.accept();
System.out.println("A client has connected");
objectOutputStream = new ObjectOutputStream(client.getOutputStream());
objectInputStream = new ObjectInputStream(client.getInputStream());
processClient();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
private void processClient() {
do {
try {
String messageFromClient = (String) objectInputStream.readObject();
// check for clients requests and handle them (database etc)
System.out.println("[CLIENT] " + messageFromClient);
} catch (IOException ex) {
Logger.getLogger(Testserver.class.getName()).log(Level.SEVERE, null, ex);
break;
} catch (ClassNotFoundException ex) {
Logger.getLogger(Testserver.class.getName()).log(Level.SEVERE, null, ex);
break;
}
} while (true);
closeConnections();
}
private void closeConnections() {
try {
objectInputStream.close();
objectInputStream.close();
client.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
public static void main(String[] args) {
new Testserver().listenForClient();
}
}
CustomerGUI
public class CustomerGUI extends JFrame implements ActionListener{
private Socket server;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private JPanel panel1;
private JButton btnAdminGUI;
private final int PORT = 5432;
public CustomerGUI() {
btnAdminGUI = new JButton("Go to Admin GUI");
try {
server = new Socket("localhost", PORT);
System.out.println("Connected to server");
objectOutputStream = new ObjectOutputStream(server.getOutputStream());
objectInputStream = new ObjectInputStream(server.getInputStream());
objectOutputStream.writeObject("from Customer");
objectOutputStream.flush();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()););
}
btnAdminGUI.addActionListener(this);
}
public void setGUI() {
add(btnAdminGUI);
setSize(300, 400);
setVisible(true);
}
public static void main(String[] args) {
new CustomerGUI().setGUI();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnAdminGUI) {
new AdminGUI().setGUI();
dispose();
}
}
}
AdminGUI
public class AdminGUI extends JFrame implements ActionListener{
private Socket server;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private JPanel panel1;
private JButton btnCustomerGUI;
private final int PORT = 5432;
public AdminGUI() {
btnCustomerGUI = new JButton("Go to Customer GUI");
try {
server = new Socket("localhost", PORT);
System.out.println("Connected to server");
objectOutputStream = new ObjectOutputStream(server.getOutputStream());
objectInputStream = new ObjectInputStream(server.getInputStream());
objectOutputStream.writeObject("from Admin");
objectOutputStream.flush();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
btnCustomerGUI.addActionListener(this);
}
public void setGUI() {
add(btnCustomerGUI);
setSize(300, 400);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnCustomerGUI) {
new CustomerGUI().setGUI();
dispose();
}
}
}
I'll post a solution this because I have done something similar recently, but I don't have a UI for it yet.
The idea is MVC, with two models, a Server and Client and there are two Views, JPanels, which can be displayed in a window/jframe/dialog, whichever is appropriate. The Controller is essentially an api for interacting with the model, for this simple example the controllers will be mixed with the models. I think this example has a lot of flaws, but I think it gives a good idea of what needs to be done.
A button starts a course of action,
serverControls.addActionListener( evt ->{ } );
The button does one of two actions, either it starts the server or it stops the server.
serverLoop.submit( ()->{
server.listen();
//should notify a listener that the server has stopped.
});
serverLoop is another thread of execution, server.listen() is a long running task. It shouldn't return until we want the server to stop listening.
The other button is on the client. It has a similar structure..
clientControls.addActionListener( evt->{
clientLoop.submit( () -> client.connect( server ) );
clientLoop.submit(
() -> SwingUtilities.invokeLater(
() -> response.setText( client.communicate() )
)
);
});
First the client is going to connect, then it communicates.
import javax.swing.*;
import java.util.concurrent.*;
public class ClientServerApp{
static class Server{
volatile boolean available = false;
public void listen(){
try{
available = true;
synchronized( this ){
wait(5000);
}
} catch(Exception e){
e.printStackTrace();
//if the server terminates unexpectedly.
}finally{
available = false;
}
}
public void stopListening(){
}
}
static class Client{
Server connected;
public void connect(Server host){
connected = host;
}
public String communicate(){
if(connected != null){
if(connected.available){
return "connected";
} else{
return "cannot connect";
}
}
return "no host";
}
}
public static void main(String[] args){
Server server = new Server();
Client client = new Client();
ExecutorService serverLoop = Executors.newSingleThreadExecutor();
JPanel serverView = new JPanel();
JButton serverControls = new JButton("start");
serverView.add( serverControls );
serverControls.addActionListener( evt ->{
if(serverControls.getText().equals("start") ){
serverControls.setText("stop");
serverLoop.submit( ()->{
server.listen();
//should notify a listener that the server has stopped.
});
} else{
server.stopListening();
serverLoop.submit( ()->{
//will be run after the listen loop has completed.
SwingUtilities.invokeLater( () - >
serverControls.setText("start")
);
});
}
} );
JPanel clientView = new JPanel();
JButton clientControls = new JButton("connect");
JTextField response = new JTextField(40);
clientView.add( clientControls );
clientView.add(response);
ExecutorService clientLoop = Executors.newSingleThreadExecutor();
System.out.println("creating client action listener");
clientControls.addActionListener( evt->{
clientLoop.submit( () -> client.connect( server ) );
clientLoop.submit( () ->
SwingUtilities.invokeLater(
() -> response.setText( client.communicate() )
)
);
});
JFrame mainWindow = new JFrame();
mainWindow.setContentPane( serverView);
mainWindow.pack();
mainWindow.setVisible(true);
JDialog clientWindow = new JDialog( mainWindow, "Client Window");
clientWindow.setContentPane(clientView);
clientWindow.pack();
clientWindow.setVisible(true);
}
}
In a more complete example, you would probably have a Listener interface, so that your swing gui can response to changes in state of the server or the client, and a controller that manages the threads.

Cannot interrupt a thread

I am implementing a Chatting program. Whenever the user clicks "START" in Player.java, it will terminates the previous Chatter thread and build a new thread to start. The Chatter thread has GUI for chatting.
I terminate the Chatter thread by the interrupt() method. I thought it will set the flag in Chatter thread so that it will be terminated by checking isInterrupted() but it is always false. But it is supposed to be true when I call interrupt() in Player.java
Here is my code:
Player.java
public class Player implements GameConstants{
/**
* This listener is used when the user clicks QUIT in the GUI.
*/
private class ControlListener implements ActionListener{
/**
* This method sends QUIT to the server when the listener is triggered.
* #param e ActionEvent
*/
#Override
public void actionPerformed(ActionEvent e){
String cmd = ((JButton)(e.getSource())).getText();
if ("START".equals(cmd)) {
//I interrupt the thread using this
if (chatThread !=null) {
System.err.println("before interruped");
chatThread.interrupt();
}
chatThread = new Chatter(ip,senderName);
chatThread.start();
}
}
}
}
Here is Chatter.java
public class Chatter extends Thread implements GameConstants{
private JTextArea log;
private String senderName;
private DataInputStream fromServer;
private DataOutputStream toServer;
private JTextField inputField;
private SoundPlayer msgSound;
private Socket socket;
private class SendListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
String msg = inputField.getText();
inputField.setText("");
try {
toServer.writeUTF(""+(new Date())+ "\n" + senderName + ": "+msg);
toServer.flush();
} catch(IOException ex) {
System.err.println(ex.getMessage());
}
}
}
public Chatter(String ip, String senderName){
this.senderName = senderName;
buildGUI();
try{
socket = new Socket(ip,CHAT_PORT);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
}catch(IOException e){
System.out.println(e.getMessage());
}
}
#Override
public void run(){
try {
while(!isInterrupted()){
String msg = fromServer.readUTF();
report(msg);
}
} catch(IOException e) {
System.err.println(e.getMessage());
}finally{
try {
socket.close();
} catch(Exception e) {
}
}
}
private void buildGUI(){
JFrame frame = new JFrame();
frame.setSize(WIDTH,HEIGHT);
frame.setTitle("Chat Room - " + senderName);
frame.setResizable(false);
// .... just building the GUI
frame.add(parentPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
When you interrupt a Thread, it may throw InterruptedException if it's waiting for some IO operations or like that. Its Interrupted flag will be cleared after Exception is thrown and will be false again.

JScrollPanel is not responding initially

I wanted to make a chat server client with GUI. Any new messages will be added as a JPanel. Initially messages added to my JScrollPanel is updating smoothly. However when i implemented the server and client to work with the GUI, the first few new messages added are never updated. Messages will only be updated to the JScrollPanel after the third add onward. Some times the adding of components ended prematurely. The client implements runnable so any new messages will be updated to the JScrollPanel via a Thread.
It seems like the GUI did not fully initialise.
this is the Client code
public static void main(String[] args) {
new Thread(new MessageClient("htf0001")).start();
MessageGUI dialog = new MessageGUI(collaID);
}
#Override
public void run() {
//loop read from server
// The default port.
int portNumber = 50000;
// The default host.
String host = "localhost";//"54.169.62.79";
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
oos = new ObjectOutputStream(clientSocket.getOutputStream());
oos.flush();
ois = new ObjectInputStream(clientSocket.getInputStream());
Staff staff = new Staff();
sendToServer(staff.connectToMessageServer(collaID));
sendToServer(staff.getMessageLog(collaID));
while(!close){
ArrayList<String> input = new ArrayList<String>();
Object o = ois.readObject();
input = (ArrayList<String>) o;
if(input.get(0).compareTo("end")!=0){
for(int i=0;i<input.size();i=i+5){
MessageGUI.addMessage(input.get(i),input.get(i+1), input.get(i+2),
input.get(i+3),input.get(i+4));
}
}
else close = true;
}
oos.close();
ois.close();
clientSocket.close();
}
catch (UnknownHostException uhe) {
JOptionPane.showMessageDialog(null,uhe.getMessage());
}
catch (IOException ioe) {
JOptionPane.showMessageDialog(null,ioe.getMessage());
}
catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
this is the GUI code part that add in the component
public static void addMessage(String date, String firstName, String lastName,
String message, String time){
String newUser = firstName + " " + lastName;
if(recentDate.compareTo(date)!=0){
JLabel newDate = new JLabel(date);
newDate.setHorizontalAlignment(SwingConstants.CENTER);
addComponent(newDate,nextLine,0,3,1);
recentDate = date;
nextLine++;
}
if(recentUser.compareTo(newUser)==0 && recentTime.compareTo(time)==0){
recentJTextArea.append("\n\n"+message);
}
else{
if(recentUser.compareTo(newUser)==0) newUser = recentUser;
JTextArea temp = new JTextArea();
temp.setFocusable(false);
temp.setBorder(BorderFactory.createTitledBorder(newUser));
temp.setLineWrap(true);
temp.setWrapStyleWord(true);
temp.setEditable(false);
temp.setText(message);
recentJTextArea = temp;
recentUser = newUser;
JLabel newTime = new JLabel(time);
newTime.setHorizontalAlignment(SwingConstants.RIGHT);
recentTime = time;
addComponent(temp,nextLine,0,2,1);
nextLine = nextLine + 1;
addComponent(newTime,nextLine,1,1,1);
nextLine = nextLine + 1;
}
invokeLater(new Runnable() {
public void run() {
ChatLogJScrollPane.getVerticalScrollBar().setValue(ChatLogJScrollPane.getVerticalScrollBar().getMaximum());
}
});
}
Seems like you are updating (ie adding the chat text) to your text areas on a thread that is not the GUI thread. Instead, you should call
SwingUtilities.invokeLater(new Runnable() {
temp.setText(message);
temp.repaint();
});
I've found the solution. I need to validate the JPanel in my JScrollPanel.
JPanel container
JScrollPanel(container)
SwingUtilities.invokeLater(new Runnable(){
container.validate();
});

How to make custom Java/JavaFX console?

It's necessary to make a custom console. I have the following code:
public class Console extends OutputStream{
private Console(ResourceBundle resourceBundle) throws IOException {
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("Console.fxml"), resourceBundle);
controller = loader.getController();
Scene scene = new Scene((Parent) loader.load());
stage = new Stage();
stage.setScene(scene);
show();
}
#Override
public void write(int b) throws IOException {
controller.append(b);
}
public static Console getInstance(ResourceBundle resourceBundle) {
if (console == null) {
try {
console = new Console(resourceBundle);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return console;
}
public void show() {
stage.show();
}
private static Console console = null;
private ConsoleController controller;
private Stage stage;
}
controller file:
public class ConsoleController implements Initializable {
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
#FXML
public void append(int i) {
textArea.appendText(String.valueOf((char) i));
}
#FXML
private TextArea textArea;
}
And all these are called from the 'start()':
#Override
public void start(Stage primaryStage) throws IOException {
...
System.setErr(new PrintStream(Console.getInstance(rb)));
}
During the exception nothing is printed in the textArea of the Console.fxml, but the following exception is thrown:
Exception in thread "JavaFX Application Thread"
Exception: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "JavaFX Application Thread"
What am I doing wrong?
------EDIT--------
After understanding that it's necessary to use several threads I have the following code:
public class Console{
private Console(ResourceBundle resourceBundle) throws IOException {
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("Console.fxml"), resourceBundle);
Parent root = (Parent) loader.load();
controller = loader.getController();
Scene scene = new Scene(root);
stage = new Stage();
stage.setScene(scene);
show();
if (errorOutputThread != null) {
errorOutputThread.interrupt();
try {
errorOutputThread.join();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
errorOutputThread = null;
}
if (outOutputThread != null) {
outOutputThread.interrupt();
try {
outOutputThread.join();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
outOutputThread = null;
}
System.err.flush();
System.out.flush();
outPipedInputStream = new PipedInputStream();
outPipedOutputStream = new PipedOutputStream(outPipedInputStream);
System.setOut(new PrintStream(outPipedOutputStream));
errorPipedInputStream = new PipedInputStream();
errorPipedOutputStream = new PipedOutputStream(errorPipedInputStream);
System.setErr(new PrintStream(errorPipedOutputStream));
outOutputThread = new Thread(new ConsoleStream(outPipedInputStream, "OUT"));
outOutputThread.setDaemon(true);
outOutputThread.start();
errorOutputThread = new Thread(new ConsoleStream(errorPipedInputStream, "ERROR"));
errorOutputThread.setDaemon(true);
errorOutputThread.start();
controller.appendText("Start Console");
}
public static Console getInstance(ResourceBundle resourceBundle) {
if (console == null) {
try {
console = new Console(resourceBundle);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return console;
}
public void show() {
stage.show();
}
private class ConsoleStream implements Runnable {
private ConsoleStream(InputStream in, String type) {
inputStream = in;
this.type = type;
}
public void run() {
try {
InputStreamReader is = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(is);
String read = null;
read = br.readLine();
while(read != null) {
controller.appendText(read + "\n");
read = br.readLine();
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
controller.appendText("Thread" + type + "started");
}
private final InputStream inputStream;
private String type;
}
private static Console console = null;
private ConsoleController controller;
private Stage stage;
private PrintStream printStream;
private PipedOutputStream customPipedOutputStream;
private PipedOutputStream errorPipedOutputStream;
private PipedOutputStream outPipedOutputStream;
private PipedInputStream customPipedInputStream;
private PipedInputStream errorPipedInputStream;
private PipedInputStream outPipedInputStream;
private Thread customOutputThread;
private Thread outOutputThread;
private Thread errorOutputThread;
}
But the result is only: "Start Console", there are no results of controller.appendText("Thread" + type + "started"); so it seems that this threads don't start. But why?
I think you have to load the form before you can get the controller instance
FXMLLoader loader = new FXMLLoader(this.getClass().getResource("Console.fxml"),resourceBundle);
Parent p = (Parent) loader.load()
controller = loader.getController();
Scene scene = new Scene(p);

Server and Client using Sockets

Are there any examples of a server and a client that use sockets, but that have send and get methods? I'm doing this networked battleship program, almost finished, but can't get the server and clients to work. I have made a chat program that only sends strings, but this time I need to send objects. I'm already frustrated, so is there any source code that already has this.
Here's the code for the client... how would you modify it to allow to send objects? Also I need to be listening for incoming objects and process them right away.
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleChat extends JFrame {
private Socket communicationSocket = null;
private PrintWriter outStream = null;
private BufferedReader inStream = null;
private Boolean communicationContinue = true;
private String disconnectString = "disconnect764*#$1";
private JMenuItem disconnectItem;
private JTextField displayLabel;
private final Color colorValues[] = { Color.black, Color.blue, Color.red, Color.green };
// set up GUI
public SimpleChat() {
super("Simple Chat");
// set up File menu and its menu items
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
// set up Activate Server menu item
JMenuItem serverItem = new JMenuItem("Activate Server");
serverItem.setMnemonic('S');
fileMenu.add(serverItem);
serverItem.addActionListener(new ActionListener() { // anonymous inner class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
setUpServer();
}
} // end anonymous inner class
); // end call to addActionListener
// set up Activate Client menu item
JMenuItem clientItem = new JMenuItem("Activate Client");
clientItem.setMnemonic('C');
fileMenu.add(clientItem);
clientItem.addActionListener(new ActionListener() { // anonymous inner class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
setUpClient();
}
} // end anonymous inner class
); // end call to addActionListener
// set up Activate Client menu item
disconnectItem = new JMenuItem("Disconnect Client/Server");
disconnectItem.setMnemonic('D');
disconnectItem.setEnabled(false);
fileMenu.add(disconnectItem);
disconnectItem.addActionListener(new ActionListener() { // anonymous inner
// class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
disconnectClientServer(true);
}
} // end anonymous inner class
); // end call to addActionListener
// set up About... menu item
JMenuItem aboutItem = new JMenuItem("About...");
aboutItem.setMnemonic('A');
fileMenu.add(aboutItem);
aboutItem.addActionListener(new ActionListener() { // anonymous inner class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(SimpleChat.this, "This is an example\nof using menus", "About",
JOptionPane.PLAIN_MESSAGE);
}
} // end anonymous inner class
); // end call to addActionListener
// set up Exit menu item
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
fileMenu.add(exitItem);
exitItem.addActionListener(new ActionListener() { // anonymous inner class
// terminate application when user clicks exitItem
public void actionPerformed(ActionEvent event) {
disconnectClientServer(true);
System.exit(0);
}
} // end anonymous inner class
); // end call to addActionListener
// create menu bar and attach it to MenuTest window
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
bar.add(fileMenu);
// set up label to display text
displayLabel = new JTextField("Sample Text", SwingConstants.CENTER);
displayLabel.setForeground(colorValues[0]);
displayLabel.setFont(new Font("Serif", Font.PLAIN, 72));
displayLabel.addActionListener(new ActionListener() { // anonymous inner
// class
// display message dialog when user selects About...
public void actionPerformed(ActionEvent event) {
sendData();
}
} // end anonymous inner class
); // end call to addActionListener
getContentPane().setBackground(Color.CYAN);
getContentPane().add(displayLabel, BorderLayout.CENTER);
setSize(500, 200);
setVisible(true);
} // end constructor
public static void main(String args[]) {
final SimpleChat application = new SimpleChat();
application.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
application.disconnectClientServer(true);
System.exit(0);
}
});
// application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void setCommunicationSocket(Socket sock) {
communicationSocket = sock;
communicationContinue = true;
disconnectItem.setEnabled(true);
}
public void setOutStream(PrintWriter out) {
outStream = out;
}
public void setInStream(BufferedReader in) {
inStream = in;
}
public void setUpServer() {
ServerThread st = new ServerThread(this);
st.start();
}
public void setUpClient() {
ClientThread st = new ClientThread(this);
st.start();
}
public void disconnectClientServer(Boolean sendMessage) {
if (communicationSocket == null)
return;
try {
// shut down socket read loop
communicationContinue = false;
disconnectItem.setEnabled(false);
// send notification to other end of socket
if (sendMessage == true)
outStream.println(disconnectString);
// sleep to let read loop shut down
Thread t = Thread.currentThread();
try {
t.sleep(500);
} catch (InterruptedException ie) {
return;
}
outStream.close();
inStream.close();
communicationSocket.close();
} catch (IOException e) {
System.err.println("Stream Read Failed.");
JOptionPane.showMessageDialog(SimpleChat.this, "Disconnection Failed", "SimpleChat", JOptionPane.PLAIN_MESSAGE);
return;
} finally {
communicationSocket = null;
}
}
public void sendData() {
if (communicationSocket != null) {
String data = displayLabel.getText();
outStream.println(data);
}
}
public void getData() {
String inputLine;
try {
while (communicationContinue == true) {
communicationSocket.setSoTimeout(100);
// System.out.println ("Waiting for Connection");
try {
while (((inputLine = inStream.readLine()) != null)) {
System.out.println("From socket: " + inputLine);
if (inputLine.equals(disconnectString)) {
disconnectClientServer(false);
return;
}
displayLabel.setText(inputLine);
}
} catch (SocketTimeoutException ste) {
// System.out.println ("Timeout Occurred");
}
} // end of while loop
System.out.println("communication is false");
} catch (IOException e) {
System.err.println("Stream Read Failed.");
JOptionPane.showMessageDialog(SimpleChat.this, "Input Stream read failed", "SimpleChat",
JOptionPane.PLAIN_MESSAGE);
return;
}
}
}
class ServerThread extends Thread {
private SimpleChat sc;
private JTextField display;
public ServerThread(SimpleChat scParam) {
sc = scParam;
}
public void run() {
ServerSocket connectionSocket = null;
try {
connectionSocket = new ServerSocket(10007);
} catch (IOException e) {
System.err.println("Could not listen on port: 10007.");
JOptionPane.showMessageDialog(sc, "Could not listen on port: 10007", "Server", JOptionPane.PLAIN_MESSAGE);
return;
}
JOptionPane.showMessageDialog(sc, "Server Socket is now activated", "Server", JOptionPane.PLAIN_MESSAGE);
Socket communicationSocket = null;
try {
communicationSocket = connectionSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
JOptionPane.showMessageDialog(sc, "Accept failed", "Server", JOptionPane.PLAIN_MESSAGE);
return;
}
JOptionPane.showMessageDialog(sc, "Comminucation is now activated", "Server", JOptionPane.PLAIN_MESSAGE);
try {
PrintWriter out = new PrintWriter(communicationSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(communicationSocket.getInputStream()));
sc.setCommunicationSocket(communicationSocket);
sc.setOutStream(out);
sc.setInStream(in);
connectionSocket.close();
sc.getData();
} catch (IOException e) {
System.err.println("Accept failed.");
JOptionPane.showMessageDialog(sc, "Creation of Input//Output Streams failed", "Server", JOptionPane.PLAIN_MESSAGE);
return;
}
}
}
class ClientThread extends Thread {
private SimpleChat sc;
public ClientThread(SimpleChat scParam) {
sc = scParam;
}
public void run() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String ipAddress = "127.0.0.1";
try {
echoSocket = new Socket(ipAddress, 10007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + ipAddress);
JOptionPane.showMessageDialog(sc, "Don't know about host: " + ipAddress, "Client", JOptionPane.PLAIN_MESSAGE);
return;
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: " + ipAddress);
JOptionPane.showMessageDialog(sc, "Couldn't get I/O for the connection to: " + ipAddress, "Client",
JOptionPane.PLAIN_MESSAGE);
return;
}
JOptionPane.showMessageDialog(sc, "Comminucation is now activated", "Client", JOptionPane.PLAIN_MESSAGE);
sc.setCommunicationSocket(echoSocket);
sc.setOutStream(out);
sc.setInStream(in);
sc.getData();
}
}
I suggest you read up on java serialization. There is an example here. Basically, there is built in serialization support. Your class needs to implement Serializable. Then you use ObjectOutputStream and ObjectInputStream to write object.
You would be well advised to use libraries that shield you from the error prone low level socket programming.
For C++ look to Boost (http://www.boost.com) or ACE (http://www.cs.wustl.edu/~schmidt/ACE.html)
For Java I only found a document that talks about the acceptor pattern http://www.hillside.net/plop/plop99/proceedings/Fernandez3/RACPattern.PDF
But I am sure there's an implementation out somewhere
Your on the right track. A chat program is a good place to start learning about sockets.
What you want is to use the ObjectOutputStream and ObjectInputStream classes. You simply have to wrap your input stream / output stream with these filters. ObjectOutputStream has a method writeObject(), and the ObjectInputStream has a corresponding readObject() method.
Most serialization examples show reading and writing objects to a file, but the same can be done using a socket stream. See http://www.acm.org/crossroads/xrds4-2/serial.html
I didn't bother to read through your piles and piles of code, but in general you can't directly send objects over the network. Network communication is just bits and bytes. If you want to send objects, you'll need to serialize them on the sending side, and de-serialize them on the receiving side. There are tons of methods of serializing, eg JSON, XML, or even Java's built-in serialization support (only recommended if both the client and server will always be Java).
You may find this code to be a decent starting point for making your own class. These are two classes I made to somewhat abstract the work needed for TCP and UDP socket protocols:
http://code.google.com/p/hivewars/source/browse/trunk/SocketData.java
http://code.google.com/p/hivewars/source/browse/trunk/UDPSocket.java
Quick dislaimer: These are kind of versions of a feature full class, I just added functionality as I needed it. However, it could help you start.

Categories