Running from jar files gives EOFException - java

I am trying to create a simple messenger application between two computers, client to server. I have created the necessary port forwards. I have two programs - one for the server and one for the client - when I test them both on my machine from my IDE (Netbeans) they work (the streams are established and I am able to send messages to and fro). But when I run the jar files (again on the same computer) the streams are established between the two programs but then are immediately disconnected since and EOFException is given.
Below please find the code in the Client program and after that the Server program
Client Program
public class ClientGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private final String serverIP = "46.11.85.22";
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ClientGUI() {
super("Client");
initComponents();
this.setVisible(true);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
connectToServer();
setupStreams();
whileChatting();
} catch (EOFException e) {
showMessage("\n " + (jtfUsername.getText()) + " terminated connection");
} catch (IOException IOe) {
IOe.printStackTrace();
} finally {
close();
}
}
private void connectToServer() throws IOException {
showMessage("Attempting Connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 8080);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams Estabished \n");
}
private void whileChatting() throws IOException {
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);;
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception occoured");
}
} while (!message.equals("SERVER - END"));
System.exit(0);
}
private void close() {
showMessage("\n Closing Application");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject(jtfUsername.getText() + " - " + message);
output.flush();
showMessage("\n" + jtfUsername.getText() + " - " + message);
} catch (IOException e) {
jtaView.append("\n Exception Occoured");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(m);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
Server Program
public class ServerGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ServerGUI() {
super("Server");
this.setVisible(true);
initComponents();
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
server = new ServerSocket(8080, 10);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (EOFException e) { // End of Stream
showMessage("\n Server ended the connection!");
} finally {
close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForConnection() throws IOException {
showMessage("Waiting for client to connect... \n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are setup \n");
}
private void whileChatting() throws IOException {
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception encountered");
}
} while (!message.contains("END"));
shutdown();
}
private static void shutdown() throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 30");
System.exit(0);
}
private void close() {
showMessage("\n Closing connections... \n");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
} catch (IOException ioE) {
jtaView.append("\n ERROR Sending");
}
}
private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(text);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
I asked my computing teacher and he told me that it might be the ports that I'm using but it still didn't work with these ports when executing the jar files. Any ideas?

Related

Using SwingWorker for client/server application stops handling requests after 10 threads

I have a server project and a client project (2 clients, a customer and an admin, from the customer GUI/Frame you can go to the admin GUI and move between GUIs as needed).
I have a button on each GUI/Frame which just sends a String to the server when it's clicked. I'm printing out the threads that are being created and I know that SwingWorkers Thread pool defaults to 10, and then it starts reusing threads.
I've noticed that once the created Threads hit 10, then the buttons to send requests to the server do not seem to send any data because the Thread pool is fully occupied.
I wanted to know how I can prevent this so a user can switch between the GUIs for x amount of time.
--
Server
public class Testserver {
private ServerSocket serverSocket;
private Socket client;
private final int PORT = 5432;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
public Testserver() {
System.out.println(Thread.currentThread().getName());
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Waiting for connection");
} catch (IOException ex) {
Logger.getLogger(Testserver.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void listenForClients() {
try {
while (true) {
client = serverSocket.accept();
System.out.println("client connected");
objectOutputStream = new ObjectOutputStream(client.getOutputStream());
objectInputStream = new ObjectInputStream(client.getInputStream());
processClient();
}
} catch (IOException ex) {
Logger.getLogger(Testserver.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Testserver().listenForClients();
});
}
private void processClient() {
SwingWorker worker = new SwingWorker<>() {
#Override
protected Void doInBackground() throws Exception {
System.out.println(Thread.currentThread().getName());
do {
try {
String messageFromClient = (String) objectInputStream.readObject();
System.out.println("[CLIENT] " + messageFromClient);
} catch (IOException ex) {
Logger.getLogger(Testserver.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Testserver.class.getName()).log(Level.SEVERE, null, ex);
}
} while (true);
}
};
worker.execute();
}
}
Customer Client
public class CustomerGUI extends JFrame implements ActionListener{
private Socket server;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private JButton btnAdminGUI,btnAddCustomer;
private final int PORT = 5432;
public CustomerGUI() {
btnAdminGUI = new JButton("Go to Admin GUI");
btnAddCustomer = new JButton("Add customer");
try {
server = new Socket("localhost", PORT);
System.out.println("Connected to server");
objectOutputStream = new ObjectOutputStream(server.getOutputStream());
objectInputStream = new ObjectInputStream(server.getInputStream());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
btnAdminGUI.addActionListener(this);
btnAddCustomer.addActionListener(this);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new CustomerGUI().setGUI();
});
}
public void setGUI() {
setLayout(new GridLayout(2,1));
add(btnAdminGUI);
add(btnAddCustomer);
setSize(300, 400);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnAdminGUI) {
new AdminGUI().setGUI();
dispose();
} else if(e.getSource() == btnAddCustomer) {
try {
objectOutputStream.writeObject("Added a customer");
objectOutputStream.flush();
} catch (IOException ex) {
Logger.getLogger(AdminGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Admin Client(Pretty much the same as Customer)
public class AdminGUI extends JFrame implements ActionListener{
private Socket server;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private JButton btnCustomerGUI, btnAddAdmin;
private final int PORT = 5432;
public AdminGUI() {
btnCustomerGUI = new JButton("Go to Customer GUI");
btnAddAdmin = new JButton("Add admin");
try {
server = new Socket("localhost", PORT);
System.out.println("Connected to server");
objectOutputStream = new ObjectOutputStream(server.getOutputStream());
objectInputStream = new ObjectInputStream(server.getInputStream());
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
btnAddAdmin.addActionListener(this);
btnCustomerGUI.addActionListener(this);
}
public void setGUI() {
setLayout(new GridLayout(2,1));
add(btnCustomerGUI);
add(btnAddAdmin);
setSize(300, 400);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnCustomerGUI) {
new CustomerGUI().setGUI();
dispose();
} else if(e.getSource() == btnAddAdmin) {
try {
objectOutputStream.writeObject("Added an admin");
objectOutputStream.flush();
} catch (IOException ex) {
Logger.getLogger(AdminGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
EDIT
Updated working method code using FixedThreadPool
private void processClient() {
System.out.println("cores: " + Runtime.getRuntime().availableProcessors());
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
executor.execute(() -> {
System.out.println(Thread.currentThread().getName());
do {
try {
String messageFromClient = (String) objectInputStream.readObject();
System.out.println("[CLIENT] " + messageFromClient);
if (messageFromClient.equalsIgnoreCase("Exit")) {
System.out.println("closed connection to " + client);
closeConnections();
System.exit(0);
}
} catch (IOException ex) {
//JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
//JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
System.out.println("ClassNotFoundException in process client: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
//JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
System.out.println("Exception in process client: " + ex.getMessage());
}
} while (true);
});
executor.shutdown();
}

Java app can't be closed even "CLOSE ON EXIT", TCP Server

I just wanna make a Server application which gets Strings and put these into a JTextArea. There are two errors I get, even no errors are showed.
the window can't be closed although I used this statement:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If the client connects to the Server, the whole window turns black. What could be the error? Here the code:
Client:
public Main() {
super("Main");
setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/images/ic.png")));
panelFields = new JPanel();
panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));
panelFields2 = new JPanel();
panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));
scrollPane = new JScrollPane();
panelFields.add(scrollPane);
getContentPane().add(panelFields);
getContentPane().add(panelFields2);
getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
setSize(326, 264);
setVisible(true);
messagesArea = new JTextArea();
scrollPane.setViewportView(messagesArea);
messagesArea.setColumns(30);
messagesArea.setRows(10);
messagesArea.setEditable(false);
startServer = new JButton("Start");
startServer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
socketConnection();
startServer.setEnabled(false);
}
});
panelFields.add(startServer);
}
And the Server connection:
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Maybe you could tell me, how I can fix those problems and also, how I can make, that the server doesn't close the socket although the client disconnects. I wanna reconnect maybe later...
You need to start your socket listener in its own thread, and you need to add a window close listener that shuts down that thread.
For example:
private ServerSocket serverSocket = null;
private boolean done = false;
private void startServer() {
Thread t = new Thread(new Runnable() {
public void Run() {
socketConnection();
});
}
t.start();
}
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
while (!done) {
try {
final Socket socket = serverSocket.accept();
Thread t = new Thread(new Runnable() {
public void Run() {
handle(socket);
}
});
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handle(Socket socket) {
if (socket == null) return;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void windowClosing(WindowEvent e) {
done = true;
socketServer.close();
}
Your button click listener should call startServer(), then your window close function would set done = true and call socketServer.close().
Now you have one thread for the UI, one thread for the socket server, and one thread for each connection to the server.

Exception in thread "Thread-0" java.net.BindException: Address already in use: JVM_Bind at

package port_channel;
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
import java.net.*;
public class ChannelPort implements Runnable {
int portNum;
int nSize;
PrintWriter[] outs ;
Listner[] listners;
ConcurrentLinkedQueue<MessageType> que;
public ChannelPort(int portNum, int networkSize) {
this.portNum = portNum;
this.nSize = networkSize;
outs = new PrintWriter[nSize];
listners = new Listner[nSize];
que = new ConcurrentLinkedQueue<MessageType>();
}
public void initialize() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(portNum);
} catch (IOException ioe) { }
for (int j = 0; j < nSize; j++) {
try {
Socket clientSocket = serverSocket.accept();
// not part of communication
outs[j] = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
listners[j] = new Listner(j, in, this);
} catch (IOException ioe) {
System.err.println("Failed in connection for j=" + j);
ioe.printStackTrace();
System.exit(-1);
}
}
System.out.println("Connections are all established.");
}
//thread
public void run() {
initialize();
for (int j = 0; j < nSize; j++) {
listners[j].start();
}
}
synchronized void gotMessage(MessageType message) {
que.offer(message);
notifyAll();
}
public synchronized MessageType receive() {
while (que.isEmpty()) {
try {
wait();
} catch (InterruptedException ire) {
ire.printStackTrace();
}
}
MessageType msg = que.poll();
System.out.println("receive: " + msg);
return msg;
}
public synchronized void broadcast(String msgStr) {
for (int j = 0; j < outs.length; j++) {
outs[j].println(msgStr);
outs[j].flush();
}
}
public int getPortNum() {
return portNum;
}
public void setPortNum(int portNum) {
this.portNum = portNum;
}
public int getnSize() {
return nSize;
}
public ConcurrentLinkedQueue<MessageType> getQue() {
return que;
}
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 2)
System.out.println("usage: java ChannelPort port-number number-of-nodes");
int portNum = Integer.parseInt(args[0]);
int numNode = Integer.parseInt(args[1]);
ChannelPort cp = new ChannelPort(portNum, numNode);
new Thread(cp).start();
Thread.sleep(60000);
System.out.println("Shutdown");
Iterator<MessageType> ite = cp.getQue().iterator();
while (ite.hasNext()) {
System.out.println(ite.next());
}
}
}
//thread
class Listner extends Thread {
int pId;
ObjectInputStream in;
ChannelPort cPort;
boolean done = false;
final int ERR_THRESHOLD = 100;
public Listner(int id, ObjectInputStream in, ChannelPort cPort) {
this.pId = id;
this.in = in;
this.cPort = cPort;
}
public void run() {
MessageType msg;
int errCnt = 0;
while(in != null) {
try {
msg = (MessageType)in.readObject();
System.out.println("process " + pId + ": " + msg);
cPort.gotMessage(msg);
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SocketException se) {
System.err.println(se);
errCnt++;
if (errCnt > ERR_THRESHOLD) System.exit(0);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Did you check the serverSocket created properly ?
You've suppressed the exception while creating the ServerSocket.
catch (IOException ioe) {
//print stack trace and see why exception occurs.
}
serverSocket might be null at 2nd try block, so serverSocket.accept() throws NPE, fix this error

How to add a Text into a List from another Client or Server?

I am trying to program my own chat but I can't get the text from one client to the next. I have the chat as a list but I can't add it. If you know how to solve it or have a idea that might work, I would love to hear it.
public class SendAction implements ActionListener {
private JButton sendButton;
private JButton sendButtonServer;
private JTextField text;
private JLabel label;
static ArrayList<String> textList = new ArrayList<String>();
static ArrayList<String> textListServer = new ArrayList<String>();
private String chatText;
public SendAction(JButton sendButton) {
this.sendButton = sendButton;
this.sendButtonServer = sendButtonServer;
}
public SendAction(JTextField text) {
this.text = text;
}
public SendAction(JLabel label) {
this.label = label;
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (e.getSource() == P2PChatClient.sendButton) {
if (P2PChatClient.text.getText().equals("")) {
} else {
textList.add("Client: " + P2PChatClient.text.getText());
System.out.println("Eingegebene ArrayList Elements: "
+ textList);
chatText = String.join(" | ", textList);
P2PChatClient.label.setText(chatText);
P2PChatClient.text.setText(null);
}
}
if (e.getSource() == P2PChatServer.sendButtonServer) {
if (P2PChatServer.textServer.getText().equals("")) {
} else {
textListServer.add("Server: "
+ P2PChatServer.textServer.getText());
System.out.println("Eingegebene ArrayList Elements: "
+ textListServer);
chatText = String.join(" | ", textListServer);
P2PChatServer.labelServer.setText(chatText);
P2PChatServer.textServer.setText(null);
}
}
}
}
another Class:
public class ChatServerSocket extends Thread {
private int port;
private P2PChatServer serverGUI;
private DataInputStream inStream;
private DataOutputStream outStream;
public ChatServerSocket(int port, P2PChatServer serverGUI) {
this.port = port;
this.serverGUI = serverGUI;
}
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Fehler: " + e.toString());
}
Socket client;
while (true) {
try {
client = server.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
inStream = new DataInputStream(in);
outStream = new DataOutputStream(out);
while (true) {
String utf = inStream.readUTF();
// File file = new File(utf);
// if (file.isFile()) {
// file.delete();
// }
SendAction.textListServer.add(utf);
// serverGUI.setMessage(utf);
}
} catch (IOException ioe) {
System.out.println("Server Fehler: " + ioe.toString());
}
}
}
public void sendText(String message) {
// P2PChatServer.send();
try {
if (message != null) {
outStream.writeUTF(message);
}
} catch (IOException ioe) {
System.out.println("Fehler beim senden im Server: "
+ ioe.toString());
} catch (NullPointerException npe) {
System.out.println("Fehler beim senden im Client: "
+ npe.toString());
}
}
}
and another:
public class ChatClientSocket extends Thread {
private String ip;
private int port;
private P2PChatClient client;
private DataInputStream inStream;
private DataOutputStream outStream;
public ChatClientSocket(String ip, int port, P2PChatClient client) {
this.port = port;
this.ip = ip;
this.client = client;
}
public void run() {
try {
Socket clientSocket = new Socket(ip, port);
InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
inStream = new DataInputStream(in);
outStream = new DataOutputStream(out);
while (true) {
String utf = inStream.readUTF();
SendAction.textList.add(utf);
// client.setMessage(utf);
}
} catch (UnknownHostException uhe) {
System.out.println("Client Fehler: " + uhe.toString());
} catch (IOException ioe) {
System.out.println("Client Fehler: " + ioe.toString());
}
}
public void sendText(String message) {
try {
if (message != null) {
outStream.writeUTF(message);
}
} catch (IOException ioe) {
System.out.println("Fehler beim senden im Client: "
+ ioe.toString());
} catch (NullPointerException npe) {
System.out.println("Fehler beim senden im Client: "
+ npe.toString());
}
}
}
I used a textarea.
With setEditable you cant edit it and scrollArea make it scrollable u know.
textArea.setEditable(false);
scrollArea = new JScrollPane(textArea);

Swing problem!(problem in showing a frame)

sorry for posting a lot of code!!I don't know that why my ListFrame doesn't work???
these are the classes.At first I run the MainServer and then I will run the MainFrame in the other package.and then by inserting a correct user name and password ,the Listframe will be shown,BUT I click on menu bar or list or delete button but nothing will happen.why?? please help me.
MainSerevr class :
public class MainServer {
static Socket client = null;
static ServerSocket server = null;
public static void main(String[] args) {
System.out.println("Server is starting...");
System.out.println("Server is listening...");
try {
server = new ServerSocket(5050);
} catch (IOException ex) {
System.out.println("Could not listen on port 5050");
System.exit(-1);
}
try {
client = server.accept();
System.out.println("Client Connected...");
} catch (IOException e) {
System.out.println("Accept failed: 5050");
System.exit(-1);
}
try {
BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean done = false;
String line;
while (!done) {
line = streamIn.readLine();
if (line.equalsIgnoreCase(".bye")) {
done = true;
} else {
System.out.println("Client says: " + line);
}
}
streamIn.close();
client.close();
server.close();
} catch (IOException e) {
System.out.println("IO Error in streams " + e);
}
}}
ListFrame:
public class ListFrame extends javax.swing.JFrame implements PersonsModelChangeListener {
private InformationClass client;
private static DefaultListModel model = new DefaultListModel();
private ListSelectionModel moDel;
/** Creates new form ListFrame */
public ListFrame(InformationClass client) {
initComponents();
this.client = client;
jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fillTable();
Manager.addListener(this);
}
private void deleteAPerson() {
int index = jList1.getSelectedIndex();
String yahooId = (String) jList1.getSelectedValue();
model.remove(index);
Manager.removeApersonFromSQL(yahooId);
int size = model.getSize();
if (size == 0) {
jButton1.setEnabled(false);
} else {
if (index == size) {
index--;
}
jList1.setSelectedIndex(index);
jList1.ensureIndexIsVisible(index);
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
AddAPerson frame = new AddAPerson(client);
frame.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
deleteAPerson();
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
MainClient.setText("");
MainClient.runAClient();
ChatFrame frame = new ChatFrame(client);
frame.setVisible(true);
}
public void fillTable() {
try {
List<InformationClass> list = null;
list = Manager.getClientListFromMySQL();
if (list == null) {
JOptionPane.showMessageDialog(this, "You should add a person to your list", "Information", JOptionPane.OK_OPTION);
return;
} else {
for (int i = 0; i < list.size(); i++) {
InformationClass list1 = list.get(i);
model.add(i, list1.getId());
}
jList1.setModel(model);
}
} catch (SQLException ex) {
Logger.getLogger(ListFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
MainClient class:
public class MainClient {
private static InformationClass info = new InformationClass();
private static Socket c;
private static String text;
public static String getText() {
return text;
}
public static void setText(String text) {
MainClient.text = text;
}
private static PrintWriter os;
private static BufferedReader is;
static boolean closed = false;
/**
* #param args the command line arguments
*/
public static void runAClient() {
try {
c = new Socket("localhost", 5050);
os = new PrintWriter(c.getOutputStream());
is = new BufferedReader(new InputStreamReader(c.getInputStream()));
String teXt = getText();
os.println(teXt);
if(c!=null&& is!=null&&os!=null){
String line = is.readLine();
System.out.println("Text received: " + line);
}
c.close();
is.close();
os.close();
} catch (UnknownHostException ex) {
System.err.println("Don't know about host");
} catch (Exception e) {
System.err.println("IOException: " + e);
}
}
}
EDIT:I have found the problem,which is because of writting MainClient.runAClient() in code ,where should I put it? please help me.
This article contains an sscce that illustrates a simple client-server GUI. You may find it instructive. If so, consider how you would address the bug found in the last line of the Echo(Kind kind) constructor.

Categories