The method writeUTF() results in java.net.SocketException: Socket closed - java

I am new to design client and server in JAVA. Now I am trying to write a client presented by a GUI to communicate with my dictionary server. The client can do add, remove or query a word (three buttons). The code in the client is as the following:
public class DictionaryClient {
private static String ip;
private static int port;
private DataInputStream input = null;
private DataOutputStream output = null;
public static void main(String[] args) {
// IP and port
ip = args[0];
port = Integer.parseInt(args[1]);
DictionaryClient client = new DictionaryClient();
client.run(ip, port);
}
public void run(String ip, int port){
GUI g = new GUI();
try(Socket socket = new Socket(ip, port);) {
// Output and Input Stream
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
g.start();
JButton c2 = (JButton)g.getComponent(2);
JButton c3 = (JButton)g.getComponent(3);
JButton c4 = (JButton)g.getComponent(4);
c2.addActionListener(new ButtonAdd(g));
c3.addActionListener(new ButtonRemove(g));
c4.addActionListener(new ButtonQuery(g));
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
//Button: Add
public class ButtonAdd implements ActionListener{
GUI g = null;
//Constructor
public ButtonAdd(GUI g){
this.g = g;
}
public void actionPerformed(ActionEvent event) {
JTextField t1 = (JTextField)g.getComponent(1);
JLabel t6 = (JLabel)g.getComponent(6);
String word = t1.getText();
String definition = t6.getText();
JLabel t5 = (JLabel)g.getComponent(5);
try {
output.writeInt(1);
output.writeUTF(word);
output.writeUTF(definition);
output.flush();
String message = input.readUTF();
t5.setText("Status: ");
t6.setText(message);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
//Button: Remove
public class ButtonRemove implements ActionListener{
GUI g = null;
//Constructor
public ButtonRemove(GUI g){
this.g = g;
}
public void actionPerformed(ActionEvent event) {
JTextField t1 = (JTextField)g.getComponent(1);
String word = t1.getText();
JLabel t6 = (JLabel)g.getComponent(6);
JLabel t5 = (JLabel)g.getComponent(5);
try {
output.writeInt(2);
output.writeUTF(word);
output.flush();
t5.setText("Status: ");
String message = input.readUTF();
t6.setText(message);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
//Button: Query
public class ButtonQuery implements ActionListener{
GUI g = null;
//Constructor
public ButtonQuery(GUI g){
this.g = g;
}
public void actionPerformed(ActionEvent event) {
JTextField t1 = (JTextField)g.getComponent(1);
String word = t1.getText();
JLabel t5 = (JLabel)g.getComponent(5);
JLabel t6 = (JLabel)g.getComponent(6);
try {
output.writeInt(3);
output.writeUTF(word);
output.flush();
String message = input.readUTF();
t6.setText(message);
t5.setText("Definition: ");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
However, when every time I clicked on one of the three buttons, it always poped out the exception: java.net.SocketException: Socket closed on the line trying to send a message to the server, such as output.writeInt(1) or output.writeUTF(word) etc.
I totally have no idea what is going wrong. Why is the socket closed? I even do not have any close() in my code. Does anyone have any idea about it? Thank you so much!

I think you might want to have a look at your server side code. The socket could well be getting closed on that side after a connect.

Related

The readObject() Method of objectOutputStream is not receiving the object written on the inputStream to the Client?

The aim is to transfer the coordinates from one Client(who is drawing) to all the Clients Connected to the Server and then draw on their respective Panels, but the readObject() in Client never seems to fetch the data. The Input Does go to the Server Properly but from Server, the Other CLients Couldn't Listen to it.
When using BufferedStream or DataInput/OutputStream any Other the input seems to lag or misbehaving. So preferring ObjectOutputStream. Snapshot of the Program.
The Client listens for the input in a background Thread listenData.
The Client Code -
public class Clients extends JFrame {
private static final long serialVersionUID = 1L;
private Coordinates crdntsToSend;
private Coordinates crdntsReceived;
private JPanel contentPane;
private Socket socket;
private ObjectOutputStream toServerPipe;
private ObjectInputStream fromServerPipe;
private JPanel paintPanel;
public Clients(String name,int port,String ip) {
setResizable(false);
setTitle("Skribbl");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,550);
createConnection(ip,port);
listen();
}
private void createConnection(String ip,int port)
{
try {
socket = new Socket(ip,port);
toServerPipe = new ObjectOutputStream(socket.getOutputStream());
fromServerPipe = new ObjectInputStream(socket.getInputStream());
toServerPipe.flush();
userInterfaceSetter();
} catch (IOException e) {
System.out.println("Port Not Found!!!");
return;
}
}
private void userInterfaceSetter()
{
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
getContentPane().setLayout(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] {0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
paintPanel = new JPanel();
paintPanel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
drawOnPanel(e.getX(),e.getY());
}
});
paintPanel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
drawOnPanel(e.getX(),e.getY());
}
});
paintPanel.setBackground(new Color(175, 238, 238));
GridBagConstraints gbcPaintPanel = new GridBagConstraints();
gbcPaintPanel.insets = new Insets(10, 10, 10, 10);
gbcPaintPanel.fill = GridBagConstraints.BOTH;
gbcPaintPanel.gridx = 0;
gbcPaintPanel.gridy = 0;
contentPane.add(paintPanel, gbcPaintPanel);
JLabel lblScore = new JLabel("Score: ");
GridBagConstraints gbclblScore = new GridBagConstraints();
gbclblScore.insets = new Insets(0, 0, 10, 0);
gbclblScore.anchor = GridBagConstraints.WEST;
gbclblScore.gridx = 0;
gbclblScore.gridy = 1;
contentPane.add(lblScore, gbclblScore);
}
private void drawOnPanel(int x,int y)
{
Graphics g = paintPanel.getGraphics();
g.fillOval(x, y, 7, 7);
sendData(x,y);
}
private void sendData(int x, int y) {
try {
crdntsToSend = new Coordinates(x,y);
toServerPipe.writeObject(crdntsToSend);
toServerPipe.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void listen()
{
SwingWorker<Void, String> listenData = new SwingWorker<Void, String>() {
boolean go = true;
String[] receivedData;
String str;
#Override
protected Void doInBackground() throws Exception {
while(go)
{
crdntsReceived = (Coordinates) fromServerPipe.readObject();
str= crdntsReceived.toString();
publish(str);
}
return null;
}
#Override
protected void process(List<String> chunks) {
receivedData = str.split(" ");
drawOnPanel(Integer.parseInt(receivedData[0]),Integer.parseInt(receivedData[1]));
}
};
listenData.execute();
}
}
ServerHandler Code(Server Thread) -
package theskribbl;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class HandleClient implements Runnable
{
private Socket[] socket;
private ObjectInputStream fromClients;
private ObjectOutputStream toClients;
private static int count = 0;
private int temp;
public HandleClient(Socket[] socket, int count)
{
HandleClient.count = count;
temp=count;
this.socket=socket;
try
{
fromClients = new ObjectInputStream(socket[count].getInputStream());
toClients = new ObjectOutputStream(socket[count].getOutputStream());
toClients.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void run()
{
int i;
Coordinates coordinate;
while(true)
{
i=0;
try
{
coordinate = (Coordinates) fromClients.readObject();
System.out.println(coordinate.toString());
while(i<=count)
{
if(i!=temp)
{
toClients = new ObjectOutputStream(socket[i].getOutputStream());
toClients.writeObject(coordinate);
toClients.flush();
}
i++;
}
}
catch (Exception e)
{
System.out.println("Something Went Wrong");
return;
}
}
}
}
code of Client - https://repl.it/#GirirajSingh/skribbl#Clients.java
code for Logging into Client - https://repl.it/#GirirajSingh/skribbl#Login.java
code for Handling the Client(Server Side) - https://repl.it/#GirirajSingh/skribbl#HandleClient.java
code of Server - https://repl.it/#GirirajSingh/skribbl#ServerClass.java
The headers that you're saying is not matching, actually they are matching because they've been initialised via the same Socket.
The same process works using DataOutputStream/DataInputStream(write()/read() ) but in this the data is getting leaked because if the mouse's dragged fast the data gets lost in between. so that's why i want to use read/writeObject() of ObjectOutputStream.
ObjectOutputStream and ObjectInputStream constructor calls must be matched - when an ObjectOutputStream is created, it sends a header which must be received when creating an ObjectInputStream.
I have no time to study the code, but it looks like the output streams are being constructed in a loop every time something is being sent by the server. Are the clients reopening the input every time they received a coordinate?
Check the documentation of ObjectOutputStream and ObjectInputStream for better explanation. Better start with a (very) simple prototype: one server, one client, and just sending a couple of (test = fixed) coordinates.
There is probably an Exception being thrown by doInBackGround() (inside the SwingWorker)! It is advised to check for this by calling the get() method after the SwingWorker terminates (inside its overridden done()) - this will thrown an ExecutionException if the computation threw an exception, which will have information about the Exception.
Add some code like the following to the SwingWorker:
#Override
protected void done() {
try {
get();
} catch (Exception ex) {
ex.printStackTrace();
}
}
ATTENTION: this code is not intended to solve the problem, only to show a possible error

Application doesn't enter thread

i'm trying to create a chat application using multhitreading functionalities and here's the code of the session class that handles connections and of the server class that accept connections:
Session class:
public class Session extends Thread{
Socket Sock;
BufferedReader din;
PrintWriter dout;
Thread receive;
Server serv;
boolean connected = false;
String lineSep = System.getProperty("line.separator");
public Session(Socket s, Server n){
super("ThreadSessions");
this.Sock = s;
this.serv = n;
}
public void run(){
try{
din = new BufferedReader(new InputStreamReader(Sock.getInputStream()));
dout = new PrintWriter(Sock.getOutputStream());
connected = true;
Receive();
}
catch(IOException ioe){
ioe.printStackTrace();
}
receive.start();
}
public void sendTo(String text){
dout.write(text);
dout.flush();
}
public void sendToAll(String text){
for(int ind = 0; ind < serv.sessions.size(); ind++){
Session s = serv.sessions.get(ind);
s.sendToAll(text);
}
}
public void Receive(){
receive = new Thread(new Runnable(){
#Override
public void run() {
receive = new Thread(new Runnable(){
String msgIn;
public void run() {
while(connected){
try{
msgIn = din.readLine();
if(msgIn != "" || msgIn != null){
System.out.println(msgIn);
msgIn = "";
}else{
}
}
catch(SocketException exc){
exc.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
});
}
}
Server class:
public class Server {
private JFrame frame;
private JTextField txtPort;
JTextArea textArea, textSessions;
String lineSep = System.getProperty("line.separator");
ServerSocket ServSock;
Socket Sock;
String port;
public JTextField textField;
int numbSess = 0, actSess = 0;
ArrayList<Session> sessions = new ArrayList<Session>();
boolean shouldRun = true;
public static void main(String[] args)
{
Server window = new Server();
window.frame.setVisible(true);
}
public Server() {
initializeComponents(); //This void initializes the graphic components
}
private void Connect(){
port = txtPort.getText();
int portN = 0;
try{
portN = Integer.parseInt(port);
}
catch(NumberFormatException exc)
{
exc.printStackTrace();
}
try{
ServSock = new ServerSocket(9081);
while(shouldRun){
Sock = ServSock.accept();
String ip = Sock.getInetAddress().getHostAddress();
Session s = new Session(Sock, this);
s.start();
sessions.add(s);
numbSess++;
}
}
catch(Exception exc){
exc.printStackTrace();
System.exit(3);
}
}
private void initializeComponents() {
[...]
Button btnConn = new JButton("Open Connection");
btnConn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Connect();
}
});
btnConn.setBackground(new Color(0, 0, 0));
btnConn.setForeground(new Color(0, 128, 0));
btnConn.setBounds(160, 13, 137, 25);
frame.getContentPane().add(btnConn);
[...]
}
What i want to do is creating a chat application that can handle more connection at the same time but instead of entering the first connection(session in my app.) it continues waiting for other connections and adding those in the arrayList.
Probably the code is full of mistakes so forgive me.
If somebody knows a better way to create a server that can handle more client's connections those are welcome.
Hope someone can help me, thanks in advance.
instead of entering the first connection(session in my app.) it continues waiting for other connections and adding those in the arrayList
This is due to how your threads are set up
Each time you make and start a session, its run method is called...
public void run()
{
Receive();
[...]
receive.start();
}
...which in turn sets up receive in Receive();
public void Receive()
{
receive = new Thread(new Runnable()
{
public void run()
{
receive = new Thread(new Runnable()
{
public void run()
{
//your actual code that you wanted to run
}
});
}
});
}
The thread created when ran, will do one thing, set up receive yet again, with the code you wanted the first time
receive = new Thread(new Runnable()
{
public void run()
{
//your actual code that you wanted to run
}
});
But after you call Receive();, you only called receive.start(); once
You'll either need to call it twice, and somehow ensure that it updated in time, or just remove the excess thread

Server issues - Java

I'm trying to make a chat function with Java. The problem is that I have two classes. One for Client and one for ClientGUI. Where the Client one has the logic parts and the ClientGUI the design. The problem is getting is in row 46 where new ListenFromServer().start(); is getting a error
No enclosing instance of type Controller is accessible. Must
qualify the allocation with an enclosing instance of type
COntroller(e.g. x.new A() where x is an instance of Controller).
So what I did was that I changedpublic class ListenFromServer extends Thread to a static. Which means public static class ListenFromServer extends Thread and now the problem that I'm getting
Error connecting to the server: java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
Controller (Client logic)
package Server;
import java.io.*;
import java.net.*;
import java.util.*;
public class Controller {
private static ObjectInputStream input;
private static ObjectOutputStream output;
private static Socket socket;
private static ClientGUI clientgui;
private static String username;
private static String server;
private static int port;
public static boolean startClient(){
try{
socket = new Socket(server, port);
}catch (Exception ex){
System.out.print("Error connecting to the server: " + ex);
return false;
}
String message = "Connection is accepted; " + socket.getInetAddress() +" - "+ socket.getPort();
System.out.println(message);
try {
input=new ObjectInputStream(socket.getInputStream());
output =new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException io) {
System.out.print("Exception creating new Input/Output Stream: "+ io);
return false;
}
**********new ListenFromServer().start();********* //The problem is here
try {
output.writeObject(username);
}
catch(IOException io) {
System.out.print("Exception doing login: " + io);
disconnect();
return false;
}
return true;
}
private void display(String message) {
if(clientgui == null)
System.out.println(message);
else
clientgui.append(message +"\n");
}
public static void sendMessage(Message message) {
try {
output.writeObject(message);
}
catch(IOException exd) {
System.out.print("Eceptionwritingtoserver: " + exd);
}
}
private static void disconnect() {
try {
if(input != null)
input.close();
}catch (Exception ex){}
try{
if(output != null)
output.close();
}catch(Exception ex){}
try{
if(socket != null)
socket.close();
}catch(Exception ex){};
if (clientgui != null)
clientgui.connectionFailed();
}
public class ListenFromServer extends Thread{
public void run() {
while(true){
try{
String message = (String) input.readObject();
if(clientgui == null){
System.out.println(message);
System.out.print(":");
}
else {
clientgui.append(message);
}
}
catch(IOException io){
System.out.print("Server has closed the connection");
if(clientgui != null)
clientgui.connectionFailed();
break;
}
catch(ClassNotFoundException classex){
}
}
}
}
}
ClientGUI
package Server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
* The Client with its GUI
*/
public class ClientGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblusername;
private JTextField textfieldusername, textfieldserver, textfieldportnumber;
private JButton btnlogin, btnlogout, btnonline;
private JTextArea textareamessage;
private boolean connected;
private Client client;
private int defaultPort;
private String defaultHost;
ClientGUI(String host, int port) {
super("Chat Client");
defaultPort = port;
defaultHost = host;
JPanel northPanel = new JPanel(new GridLayout(2,2));
JPanel serverAndPort = new JPanel(new GridLayout(1,2, 2, 2));
JLabel lblserveraddress = new JLabel("Server Address: ");
JLabel lblchat = new JLabel(" #BallIsLife");
JLabel lblportnumber = new JLabel("Port Number: ");
textfieldserver = new JTextField(host);
textfieldserver.setHorizontalAlignment(SwingConstants.LEFT);
textfieldserver.setFont(new Font("Tahoma", Font.PLAIN, 20));
textfieldportnumber = new JTextField("" + port);
textfieldportnumber.setFont(new Font("Tahoma", Font.PLAIN, 20));
textfieldportnumber.setHorizontalAlignment(SwingConstants.LEFT);
lblserveraddress.setFont(new Font("Tahoma", Font.PLAIN, 19));
serverAndPort.add(lblserveraddress);
serverAndPort.add(textfieldserver);
serverAndPort.add(lblchat);
serverAndPort.add(lblportnumber);
serverAndPort.add(textfieldportnumber);
lblchat.setForeground(Color.RED);
lblportnumber.setFont(new Font("Tahoma", Font.PLAIN, 19));
northPanel.add(serverAndPort);
getContentPane().add(northPanel, BorderLayout.NORTH);
JPanel panelbtn = new JPanel();
northPanel.add(panelbtn);
btnlogin = new JButton("Login");
panelbtn.add(btnlogin);
btnlogin.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnlogin.addActionListener(this);
btnonline = new JButton("Online");
panelbtn.add(btnonline);
btnonline.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnonline.addActionListener(this);
btnonline.setEnabled(false);
btnlogout = new JButton("Logout");
panelbtn.add(btnlogout);
btnlogout.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnlogout.addActionListener(this);
btnlogout.setEnabled(false);
JButton btnPicture = new JButton("Picture");
btnPicture.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnPicture.setEnabled(false);
panelbtn.add(btnPicture);
textareamessage = new JTextArea("Welcome to the #BallIsLife Chat room.\n");
textareamessage.setFont(new Font("Monospaced", Font.PLAIN, 15));
textareamessage.setLineWrap(true);
textareamessage.setEditable(false);
JPanel centerPanel = new JPanel(new GridLayout(1,1));
JScrollPane scrollPane = new JScrollPane(textareamessage);
centerPanel.add(scrollPane);
getContentPane().add(centerPanel, BorderLayout.CENTER);
JPanel southPanel = new JPanel();
getContentPane().add(southPanel, BorderLayout.SOUTH);
lblusername = new JLabel("Enter your username", SwingConstants.CENTER);
lblusername.setFont(new Font("Tahoma", Font.PLAIN, 15));
southPanel.add(lblusername);
textfieldusername = new JTextField("Write your username here.");
textfieldusername.setFont(new Font("Tahoma", Font.PLAIN, 14));
textfieldusername.setColumns(50);
southPanel.add(textfieldusername);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(823, 665);
setVisible(true);
}
//Logiken
void append(String str) {
textareamessage.append(str);
textareamessage.setCaretPosition(textareamessage.getText().length() - 1);
}
void connectionFailed() {
btnlogin.setEnabled(true);
btnlogout.setEnabled(false);
btnonline.setEnabled(false);
lblusername.setText("Enter your username");
textfieldusername.setText("Write your username here");
textfieldportnumber.setText("" + defaultPort);
textfieldserver.setText(defaultHost);
textfieldserver.setEditable(false);
textfieldportnumber.setEditable(false);
textfieldusername.removeActionListener(this);
connected = false;
}
//
public void actionPerformed(ActionEvent e) {
Object button = e.getSource();
if(button == btnlogout) {
Controller.sendMessage(new Message("", Message.LOGOUT)); //Ändra till Chatmessage klass
btnlogin.setText("Login");
return;
}
if(button == btnonline) {
Controller.sendMessage(new Message("", Message.ONLINE)); //Ändra till Chatmessage klass
return;
}
if(connected) {
Controller.sendMessage(new Message(textfieldusername.getText(), Message.MESSAGE)); //Ändra till Chatmessage klass
textfieldusername.setText("");
return;
}
if(button == btnlogin) {
String username = textfieldusername.getText();
if(username.length() == 0)
return;
String server = textfieldserver.getText();
if(server.length() == 0)
return;
String portNumber = textfieldportnumber.getText();
if(portNumber.length() == 0)
return;
int port = 0;
try {
port = Integer.parseInt(portNumber);
}
catch(Exception en) {
return;
}
client = new Client(server, username, port, this);
if(!Controller.startClient())
return;
}
connected = true;
textfieldusername.setText("");
btnlogin.setText("Send message");
btnlogin.setEnabled(true);
btnlogout.setEnabled(true);
btnonline.setEnabled(true);
textfieldserver.setEditable(false);
textfieldportnumber.setEditable(false);
textfieldusername.addActionListener(this);
}
// to start the whole thing the server
public static void main(String[] args) {
new ClientGUI("localhost", 1500);
}
}
Server
package Server;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* The server that can be run both as a console application or a GUI
*/
public class Server {
// a unique ID for each connection
private static int uniqueId;
// an ArrayList to keep the list of the Client
private ArrayList<ClientThread> al;
// if I am in a GUI
private ServerGUI sg;
// to display time
private SimpleDateFormat sdf;
// the port number to listen for connection
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
/*
* server constructor that receive the port to listen to for connection as parameter
* in console
*/
public Server(int port) {
this(port, null);
}
public Server(int port, ServerGUI sg) {
// GUI or not
this.sg = sg;
// the port
this.port = port;
// to display hh:mm:ss
sdf = new SimpleDateFormat("HH:mm:ss");
// ArrayList for the Client list
al = new ArrayList<ClientThread>();
}
public void start() {
keepGoing = true;
/* create socket server and wait for connection requests */
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept(); // accept connection
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket); // make a thread of it
al.add(t); // save it in the ArrayList
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("localhost", port);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendRoom(null,time + "\n");
}
/*
* to broadcast a message to all Clients
*/
private synchronized void broadcast(String message) {
// add HH:mm:ss and \n to the message
String time = sdf.format(new Date());
String messageLf = time + " " + message + "\n";
// display message on console or GUI
if(sg == null)
System.out.print(messageLf);
else
sg.appendRoom(messageLf,null); // append in the room window
// we loop in reverse order in case we would have to remove a Client
// because it has disconnected
for(int i = al.size(); --i >= 0;) {
ClientThread ct = al.get(i);
// try to write to the Client if it fails remove it from the list
if(!ct.writeMsg(messageLf)) {
al.remove(i);
display("Disconnected Client " + ct.username + " removed from list.");
}
}
}
// for a client who logoff using the LOGOUT message
synchronized void remove(int id) {
// scan the array list until we found the Id
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
// found it
if(ct.id == id) {
al.remove(i);
return;
}
}
}
/*
* To run as a console application just open a console window and:
* > java Server
* > java Server portNumber
* If the port number is not specified 1500 is used
*/
public static void main(String[] args) {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1500;
switch(args.length) {
case 1:
try {
portNumber = Integer.parseInt(args[0]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Server [portNumber]");
return;
}
case 0:
break;
default:
System.out.println("Usage is: > java Server [portNumber]");
return;
}
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// the Username of the Client
String username;
// the only type of message a will receive
Message cm;
// the date I connect
String date;
// Constructore
ClientThread(Socket socket) {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output Streams");
try
{
// create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
username = (String) sInput.readObject();
display(username + " just connected.");
}
catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return;
}
// have to catch ClassNotFoundException
// but I read a String, I am sure it will work
catch (ClassNotFoundException e) {
}
date = new Date().toString() + "\n";
}
// what will run forever
public void run() {
// to loop until LOGOUT
boolean keepGoing = true;
while(keepGoing) {
// read a String (which is an object)
try {
cm = (Message) sInput.readObject();
}
catch (IOException e) {
display(username + " Exception reading Streams: " + e);
break;
}
catch(ClassNotFoundException e2) {
break;
}
// the messaage part of the ChatMessage
String message = cm.getMessage();
// Switch on the type of message receive
switch(cm.getType()) {
case Message.MESSAGE:
broadcast(username + ": " + message);
break;
case Message.LOGOUT:
display(username + " disconnected with a LOGOUT message.");
keepGoing = false;
break;
case Message.ONLINE:
writeMsg("List of the users connected at " + sdf.format(new Date()) + "\n");
// scan al the users connected
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
writeMsg((i+1) + ") " + ct.username + " since " + ct.date);
}
break;
}
}
// remove myself from the arrayList containing the list of the
// connected Clients
remove(id);
close();
}
// try to close everything
private void close() {
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}
/*
* Write a String to the Client output stream
*/
private boolean writeMsg(String msg) {
// if Client is still connected send the message to it
if(!socket.isConnected()) {
close();
return false;
}
// write the message to the stream
try {
sOutput.writeObject(msg);
}
// if an error occurs, do not abort just inform the user
catch(IOException e) {
display("Error sending message to " + username);
display(e.toString());
}
return true;
}
}
}
ServerGUI
package Server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/*
* The server as a GUI
*/
public class ServerGUI extends JFrame implements ActionListener, WindowListener {
private static final long serialVersionUID = 1L;
// the stop and start buttons
private JButton stopStart, saveLog;
// JTextArea for the chat room and the events
private JTextArea chat;
// private JTextArea event;
// The port number
private JTextField tfPortNumber;
// my server
private Server server;
// server constructor that receive the port to listen to for connection as
// parameter
ServerGUI(int port) {
super("Chat Server");
server = null;
// in the NorthPanel the PortNumber the Start and Stop buttons
JPanel north = new JPanel();
north.add(new JLabel("Port number: "));
tfPortNumber = new JTextField("" + port);
north.add(tfPortNumber);
// to stop or start the server, we start with "Start"
stopStart = new JButton("Start");
stopStart.addActionListener(this);
saveLog = new JButton("Save log");
saveLog.addActionListener(this);
north.add(stopStart);
north.add(saveLog);
add(north, BorderLayout.NORTH);
// the event and chat room
JPanel center = new JPanel(new GridLayout());
chat = new JTextArea(120, 20);
chat.setEditable(false);
chat.setWrapStyleWord(true);
chat.setLineWrap(true);
appendRoom(null, "Chat room and Events log for server.\n");
center.add(new JScrollPane(chat));
// event = new JTextArea(80,80);
// event.setEditable(false);
// appendEvent("Events log.\n");
// center.add(new JScrollPane(event));
add(center);
// need to be informed when the user click the close button on the frame
addWindowListener(this);
setSize(450, 600);
setVisible(true);
}
public void writeLog() {
try {
JFileChooser chooser = new JFileChooser();
String content = chat.getText();
int actionDialog = chooser.showSaveDialog(this);
content = content.replaceAll("(?!\\r)\\n", "\r\n");
if (actionDialog == JFileChooser.APPROVE_OPTION) {
File file = new File(chooser.getSelectedFile() + ".txt");
// if file doesnt exists, then create it
// if (!file.exists()) {
// file.createNewFile();
// }
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
}
} catch (IOException ee) {
ee.printStackTrace();
}
// JFileChooser chooser = new JFileChooser();
// // chooser.setCurrentDirectory(new File("./"));
// int actionDialog = chooser.showSaveDialog(this);
// if (actionDialog == JFileChooser.APPROVE_OPTION) {
// File fileName = new File(chooser.getSelectedFile() + "");
// if (fileName == null)
// // return;
// if (fileName.exists()) {
// actionDialog = JOptionPane.showConfirmDialog(this,
// "Replace existing file?");
// if (actionDialog == JOptionPane.NO_OPTION)
// return;
// }
// try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
// new FileOutputStream(fileName), "ISO-8859-1"))) {
// bw.write(saveText);
// // bw.newLine();
// bw.flush();
// }
// }
}
// append message to the two JTextArea
// position at the end
void appendRoom(String chatStr, String eventStr) {
chat.append(chatStr);
chat.append(eventStr);
// chat.setCaretPosition(chat.getText().length() - 1);
}
// void appendEvent(String str) {
// event.append(str);
// event.setCaretPosition(chat.getText().length() - 1);
//
// }
// start or stop where clicked
public void actionPerformed(ActionEvent e) {
// if running we have to stop
if (e.getSource() == saveLog) {
writeLog();
} else if (e.getSource() == stopStart) {
if (server != null) {
server.stop();
server = null;
tfPortNumber.setEditable(true);
stopStart.setText("Start");
return;
}
// OK start the server
int port;
try {
port = Integer.parseInt(tfPortNumber.getText().trim());
} catch (Exception er) {
appendRoom(null, "Invalid port number");
return;
}
// ceate a new Server
server = new Server(port, this);
// and start it as a thread
new ServerRunning().start();
stopStart.setText("Stop");
tfPortNumber.setEditable(false);
}
}
/*
* A thread to run the Server
*/
class ServerRunning extends Thread {
public void run() {
server.start(); // should execute until if fails
// the server failed
stopStart.setText("Start");
tfPortNumber.setEditable(true);
appendRoom(null, "Server closed\n");
server = null;
}
}
// entry point to start the Server
public static void main(String[] arg) {
// start server default port 1500
new ServerGUI(1500);
}
/*
* If the user click the X button to close the application I need to close
* the connection with the server to free the port
*/
public void windowClosing(WindowEvent e) {
// if my Server exist
if (server != null) {
try {
server.stop(); // ask the server to close the conection
} catch (Exception eClose) {
}
server = null;
}
// dispose the frame
dispose();
System.exit(0);
}
// I can ignore the other WindowListener method
public void windowClosed(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
// /*
// * A thread to run the Server
// */
// class ServerRunning extends Thread {
// public void run() {
// server.start(); // should execute until if fails
// // the server failed
// stopStart.setText("Start");
// tfPortNumber.setEditable(true);
// appendRoom(null, "Server closed\n");
// server = null;
// }
// }
}
Message
package Server;
import java.io.Serializable;
//Klassen som kollar vad för typ av message
public class Message implements Serializable {
protected static final long serialVersionUID = 42L;
static final int ONLINE = 0;
static final int MESSAGE = 1;
static final int LOGOUT = 2;
private int SAVELOG = 3;
private String message;
private int type;
public Message(String message, int type){
this.type = type;
this.message = message;
}
public int getType(){
return type;
}
public String getMessage(){
return message;
}
}
Make your inner class ListenFromServer static, since you are referring to it from a static method
public class Controller {
...
public static class ListenFromServer {
...
}
}

java swing frame not closing with X

hello guys i am working on program in which i have to perform a certain task after which i can close the window also.. obviously but it is not closing the window...
my main class is like
public class laudit {
public static void main(String[] arg){
SwingUtilities.invokeLater( new Runnable(){
public void run(){
JFrame frame = new mainFrame("Linux Audit");
frame.setVisible(true);
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
Second class with panel is...following in which i am starting a ssh connection but it is not stoping as it is supposed to after completion..
public class panel extends JPanel {
String shost;
String suser;
String spass;
int sport;
public int getsport() {
return this.sport;
}
public String getshost() {
return this.shost;
}
public String getsuser() {
return this.suser;
}
public String getspass() {
return this.spass;
}
public panel(){
Dimension size = getPreferredSize();
size.width = 680;
size.height = 600;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Linux Audit"));
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
JLabel labelhost = new JLabel("Host ");
JLabel labeluser = new JLabel("User name ");
JLabel labelpass = new JLabel("Password ");
JLabel labelport = new JLabel("Port ");
final JTextField host = new JTextField(15);
final JTextField user = new JTextField(15);
final JTextField pass=(JTextField)new JPasswordField(15);
final JTextField port = new JTextField(15);
final JButton start = new JButton("Start Audit");
//layout design
gc.anchor = GridBagConstraints.LINE_END;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx=0;
gc.gridy=0;
add(labelhost,gc);
gc.gridx=0;
gc.gridy=1;
add(labeluser,gc);
gc.gridx=0;
gc.gridy=2;
add(labelpass,gc);
gc.gridx=0;
gc.gridy=3;
add(labelport,gc);
gc.anchor = GridBagConstraints.LINE_START;
gc.gridx=1;
gc.gridy=0;
add(host,gc);
gc.gridx=1;
gc.gridy=1;
add(user,gc);
gc.gridx=1;
gc.gridy=2;
add(pass,gc);
gc.gridx=1;
gc.gridy=3;
add(port,gc);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.weighty=10;
gc.gridx=1;
gc.gridy=4;
add(start,gc);
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String shost = host.getText();
String suser = user.getText();
String spass = pass.getText();
String sportb = port.getText();
int sport = Integer.parseInt(sportb);
sshConnection s = new sshConnection();
try {
s.Connection(shost,suser,spass,sport);
} catch (JSchException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
here is the ssh connection i am very new to java programming
public class sshConnection {
public void Connection (String sHost,String sUser,String sPass,int sPort)throws JSchException, IOException{
String sshhost = sHost;
String sshuser = sUser;
String sshpass = sPass;
int sshport = sPort;
/*System.out.println(sshhost);
System.out.println(sshuser);
System.out.println(sshport);
System.out.println(sshpass);*/
String endLineStr = " # ";
JSch shell = new JSch();
// get a new session
Session session = shell.getSession(sshuser, sshhost, sshport);
// set user password and connect to a channel
session.setUserInfo(new SSHUserInfo(sshpass));
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
//file start
File f = new File("Result.txt");
if(!f.exists())
{
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
FileOutputStream fos = new FileOutputStream(f);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
} //file end
// send ls command to the server
dataOut.writeBytes("ls -la\r\n");
dataOut.flush();
// and print the response
String line = dataIn.readLine();
System.out.println(line);
while(!line.endsWith(endLineStr)) {
System.out.println(line);
line = dataIn.readLine();
}
dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
} }
class SSHUserInfo implements UserInfo {
private String sshpass;
SSHUserInfo(String sshpass) {
this.sshpass = sshpass;
}
public String getPassphrase() {
return null;
}
public String getPassword() {
return sshpass;
}
public boolean promptPassword(String arg0) {
return true;
}
public boolean promptPassphrase(String arg0) {
return true;
}
public boolean promptYesNo(String arg0) {
return true;
}
public void showMessage(String arg0) {
System.out.println(arg0);
}
}
Please help me out everything is working fine except this flaw...
Thanks..
The most likely cause of your problem is to do with sshConnection#Connection. This is likely blocking the Event Dispatching Thread, preventing it from processing any new events, like the window closing event.
You need to overload the connection to a seperate thread, for example...
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String shost = host.getText();
String suser = user.getText();
String spass = pass.getText();
String sportb = port.getText();
int sport = Integer.parseInt(sportb);
SSHTask task = new SSTask(shost, suser, spass, sport);
Thread thread = new Thread(task);
thread.start();
}
});
SSHTask class
public class SSHTask implements Runnable {
private String host;
private String user;
private String pass;
private int port;
public SSHTask(String host, String user, String pass, int port) {
this.host = host;
this.user = user;
this.pass = pass;
this.port = port;
}
public void run() {
sshConnection s = new sshConnection();
try {
s.Connection(host,user,pass,port);
} catch (JSchException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Take a look at Concurrency for more details.
If you are going to need to interact with the UI from this Thread, you would be better of using a SwingWorker, see Concurrency in Swing for details
Updated
If you still have problems. One other thing you could try is make the Thread a daemon thread...
SSHTask task = new SSTask(shost, suser, spass, sport);
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
This is a little harsh and there is still no guarantee that the system will exit while the you have a connection open...

Starting a thread in a Swing event

I'm working on the client side application of the client/server chat I'm doing for learning experience. My problem is I can't seem to get the socket and swing,both to run at the same time.
What I want to is, when the user opens a JOpionsPane and enters the hostname and port number, clicks okay, then they are connected. When the socket information was hardcoded it worked fine, but now I'm trying to get the users input for it.
What's meant to happen is, action listener is supposed to create the new SocketManager object that handles communication. Event though it says it's connected, it doesn't run. When I create the new SocketManager object and run it on a new thread it connects and revives messages form the server, but then the swings freezes and I have to end the process to shut it down.
Should I start it on a new worker thread or something? Maybe it's just because I'm tired, but I'm out of ideas.
EDIT
I updated my ActLis.class and SocketManager.class with the suggestion of adding a new thread for my SocketManager object 'network'. When I try and use 'network' though it returns null for some reason.
ActLis.clss
package com.client.core;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ActLis implements ActionListener {
private Main main = new Main();;
private JTextField ipadress = new JTextField(),
portnumber = new JTextField(),
actionField;
private String username;
final JComponent[] ipinp = new JComponent[]{new JLabel("Enter Hostname (IP Adress): "),
ipadress,
new JLabel("Enter Port number: "), portnumber};
private SocketManager network;
private Window win;
public ActLis(){
}
public ActLis(JTextField t, Window w){
actionField = t;
win = w;
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if(cmd == "Exit"){
System.exit(0);
} else if(cmd == "Connect to IP"){
try{
JOptionPane.showMessageDialog(null, ipinp, "Connect to IP", JOptionPane.PLAIN_MESSAGE);
if(network != null){
network.close();
}
network = new SocketManager(ipadress.getText(),Integer.parseInt(portnumber.getText()));
network.setGUI(win);
Thread t = new Thread(network);
t.start();
JOptionPane.showMessageDialog(null, "Connected to chat host successfully!","Connected", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception ee){
JOptionPane.showMessageDialog(null, "Could not connect. Check IP adress or internet connection","Error - Could not connect", JOptionPane.ERROR_MESSAGE);
ee.printStackTrace();
}
} else if (cmd == "chatWriter"){
if( actionField.getText() != ""){
try{
network.send(actionField.getText());
win.updateChat(actionField.getText());
actionField.setText("");
actionField.requestFocus();
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "You are not connected to a host. (File -> Connect to IP)","Error - Not Connected", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
} else if (cmd == "setUsername"){
username = actionField.getText();
network.send("USERNAME:" + username);
}
}
}
Main.class
package com.client.core;
import javax.swing.JFrame;
public class Main extends JFrame{
private SocketManager network;
public static void main(String[] args){
Main main = new Main();
main.run();
}
private void run(){
Window win = new Window();
win.setVisible(true);
}
}
SocketManager.class
package com.client.core;
import java.io.*;
import java.net.*;
public class SocketManager implements Runnable {
private Socket sock;
private PrintWriter output;
private BufferedReader input;
private String hostname;
private int portnumber;
private String message;
private Window gui;
public SocketManager(String ip, int port){
try{
hostname = ip;
portnumber = port;
}catch(Exception e){
System.out.println("Client: Socket failed to connect.");
}
}
public synchronized void send(String data){
try{
//System.out.println("Attempting to send: " + data);
output.println(data);
output.flush();
//System.out.println("Message sent.");
}catch(Exception e){
System.out.println("Message could not send.");
}
}
public synchronized void setGUI(Window w){
gui = w;
}
public synchronized void connect(){
try{
sock = new Socket(hostname,portnumber);
}catch(Exception e){
}
}
public synchronized Socket getSocket(){
return sock;
}
public synchronized void setSocket(SocketManager s){
sock = s.getSocket();
}
public synchronized void close(){
try{
sock.close();
}catch(Exception e){
System.out.println("Could not close connection.");
}
output = null;
input = null;
System.gc();
}
public synchronized boolean isConnected(){
return (sock == null) ? false : (sock.isConnected() && !sock.isClosed());
}
public synchronized void listenStream(){
try {
while((message = input.readLine()) != null){
System.out.println("Server: " + message);
gui.updateChat(message);
}
} catch (Exception e) {
}
}
#Override
public void run() {
try {
sock = new Socket(hostname,portnumber);
output = new PrintWriter(sock.getOutputStream(),true);
input = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
while(true){
listenStream();
}
} catch (Exception e) {
System.out.println("Run method fail. -> SocketManager.run()");
}finally{
try {
sock.close();
} catch (Exception e) {
}
}
}
}
Window.class
package com.client.core;
import java.awt.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
private SocketManager network;
private JPanel window = new JPanel(new BorderLayout()),
center = new JPanel(new BorderLayout()),
right = new JPanel(new BorderLayout()),
display = new JPanel( new BorderLayout()),
chat = new JPanel(),
users = new JPanel(new BorderLayout());
private JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50),
listOfUsers = new JTextArea("None Online");
private JTextField chatWrite = new JTextField(),
userSearch = new JTextField(10),
username = new JTextField();
private JScrollPane userList = new JScrollPane(listOfUsers),
currentChat = new JScrollPane(chatBox);
private JMenuBar menu = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem exit = new JMenuItem("Exit"),
ipconnect = new JMenuItem("Connect to IP");
private JComponent[] login = new JComponent[]{new JLabel("Username:"), username};
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
//Panels
listOfUsers.setLineWrap(true);
listOfUsers.setEditable(false);
display.setBackground(Color.black);
chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
chat.setBackground(Color.blue);
users.setBackground(Color.green);
//TextFields
addChatArea();
//Menu bar
addMenuBar();
//Adding the main panels.
addPanels();
//Listeners
addListeners();
for(int x = 0; x < 1; x++){
login();
}
}
private void login(){
JOptionPane.showMessageDialog(null, login, "Log in", JOptionPane.PLAIN_MESSAGE);
}
private void addChatArea(){
chatBox.setEditable(false);
userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
currentChat.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
users.add(userList);
users.add(userSearch, BorderLayout.NORTH);
chat.add(currentChat);
chat.add(chatWrite);
chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
private void addMenuBar(){
file.add(ipconnect);
file.add(exit);
menu.add(file);
}
private void addPanels(){
right.add(users);
center.add(display, BorderLayout.CENTER);
center.add(chat, BorderLayout.SOUTH);
window.add(center, BorderLayout.CENTER);
window.add(right, BorderLayout.EAST);
window.add(menu, BorderLayout.NORTH);
add(window);
}
private void addListeners(){
username.addActionListener(new ActLis(username, this));
chatWrite.addActionListener(new ActLis(chatWrite, this));
username.setActionCommand("setUsername");
chatWrite.setActionCommand("chatWriter");
ipconnect.addActionListener(new ActLis());
exit.addActionListener(new ActLis());
}
public void setNetwork(SocketManager n){
network = n;
}
public void updateChat(String s){
chatBox.setText(chatBox.getText() + "\n" + s);
}
}
Ok #Zexanima you have create a Socket class for socket manager. Something like this:
public class YouSocketClass {
static public Socket socket = null;
static public InputStream in = null;
static public OutputStream out = null;
public YouSocketClass() {
super();
}
public static final Socket getConnection(final String ip, final int port, final int timeout) {
try {
socket = new Socket(ip, port);
try {
socket.setSoTimeout(timeout);
} catch(SocketException se) {
log("Server Timeout");
}
in = socket.getInputStream();
out = socket.getOutputStream();
} catch(ConnectException e) {
log("Server name or server ip is failed. " + e.getMessage());
e.printStackTrace();
} catch(Exception e) {
log("ERROR Socket: " + e.getMessage() + " " + e.getCause());
e.printStackTrace();
}
return socket;
}
public static void closeConnection() {
try {
if(socket != null) {
if(in != null) {
if(out != null) {
socket.close();
in.close();
out.close();
}
}
}
} catch(Exception e2) {
e2.printStackTrace();
}
}
private static Object log(Object sms) {
System.out.println("Test Socket1.0: " + sms);
return sms;
}
}
I hope that serve. :)

Categories