I have this problem that I can't close current form after receiving message from server, I have implemented a thread class as I need to exchange message from a server, the problem that I am facing now is I cant close the current form after receiving start message from the server, opening new form is working correctly, but when I'm coming to close the current form it not working !! I don't know how to solve this problem so I need help with that
public class StartForm extends javax.swing.JFrame {
// needed info about the current user
public static StartForm form= new StartForm() ;
private String name;
private String currentUsers;
private int id ;
private static int time ;
public static Socket socket;
public boolean firstFlag;
private boolean close=false;
public static PrintWriter printWriter;
public static BufferedReader bufferedReader;
public static Scanner reader;
public static java.lang.Thread thread2;
public void setName (String name){
this.name=name;}
public String getName (){
return this.name;}
public void setCurrentUsers (String currentUsers){
this.currentUsers=currentUsers;}
public String getCurrentUsers (){
return this.currentUsers;}
public void setId (int id){
this.id=id;}
public int getId (){
return this.id;}
public void setTime (int time){
this.time=time;}
public int getTime (){
return this.time;}
public void setSocket (Socket socket){
this.socket=socket;
}
public Socket getSocket (){
return this.socket;}
public void setFirstFlag (boolean firstFlag){
this.firstFlag=firstFlag;}
public boolean getFirstFlag (){
return this.firstFlag;}
/**
* Creates new form StartForm
*/
public StartForm() {
initComponents();
}
// constructor to initialize
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
if (testInput(jTextField1.getText())){
// PrintWriter printWriter;
// read the inserted time and falidate it if it number send it to the server to notify the other users
printWriter.println("time:"+jTextField1.getText());
jButton2.setEnabled(false);
jTextField1.setEnabled(false);
jButton1.setEnabled(true);
}
else {
//if time inserted is not number unaccepted
JOptionPane.showMessageDialog(null, "only insert numbers");
jTextField1.setText("");
}
// TODO add your handling code here:
}
private void formWindowActivated(java.awt.event.WindowEvent evt) {
// initiate the needed reader and writer objects
try {
printWriter = new PrintWriter(socket.getOutputStream(),true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// starting the thread
Thread thread = new Thread (this.getId(),form);
thread2 = new java.lang.Thread(thread);
thread2.start();
} catch (IOException ex) {
Logger.getLogger(StartForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void formWindowClosed(java.awt.event.WindowEvent evt) {
// close the frame
this.dispose();
System.exit(0); }
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
printWriter.println("ready"+id);
jLabel8.show();
this.disable();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
form.setVisible(true);
}
});
}
public class Thread implements Runnable {
private int idd;
private StartForm form3;
public Thread(int id, StartForm form2){
idd=id;
form3=form;
}
public void run()
{
try {
String message="";
while((message=bufferedReader.readLine())!=null){
{
else if (message.substring(0,5).equals("start")){
GameForm gameFrame= new GameForm();
int trunid =Integer.parseInt(message.substring(5));
System.out.println("$$$$$ on the thread "+ trunid);
if (id==trunid)
gameFrame.setTurn(true);
else gameFrame.setTurn(false);
gameFrame.setId(idd);
form3.setVisible(false);
gameFrame.setVisible(true);
}
else {
jTextArea2.append(message); }
}
}
} catch (IOException ex) {
Logger.getLogger(StartForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
}
Related
i have an error in this code that's the thread set 2 value instead of one when the program start , the program mustn't set the next value before get the current
this is the main class
class DATA
{
private int value=0;
Lock lock;
Condition co;
Boolean IstReady=false;
public DATA()
{
IstReady=false;
lock = new ReentrantLock();
co=lock.newCondition();
}
public void set(int x) throws InterruptedException
{
lock.lock();// try
while(IstReady==true)
co.await();
value=x;
IstReady=true;
co.signal();
lock.unlock();
}
public int get()
{
int ret=0;
try{
lock.lock();
while(IstReady==false)
co.await();
ret=value;
co.signal();
//lock.unlock();
}
catch(Exception e)
{
System.out.println(e);
}
finally{
lock.unlock();
IstReady=false;
}
return ret;
}
}
}
}
and this the set() and get() class
class setter extends Thread
{
DATA D;
public setter(DATA X)
{
D=X;
}
#Override
public void run()
{
Random T=new Random();
while(true)
{
try {
int M=T.nextInt(1000);
System.out.println("setter set"+M);
D.set(M);
} catch (InterruptedException ex) {
Logger.getLogger(setter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class Newtest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
DATA x=new DATA();
setter s=new setter(x);
getter g=new getter(x);
s.start();
g.start();
}
}
i think the error is in the set() and get() method in DATA class
I have a a GPS receptor. I create a class to retrieve all the GPS data on my Eclipse Console.
(This is the code of makia42)
public class COM implements Runnable{
static Thread myThread=null;
static BufferedReader br;
static BufferedWriter wr;
static InputStreamReader isr;
static OutputStreamWriter osw;
static java.io.RandomAccessFile port;
public COM(){ /**Constructeur*/
myThread=new Thread(this);
}
public void start(){
try {
port=new java.io.RandomAccessFile("COM3","rwd");
port.writeBytes("\r\n");
port.writeBytes("c,31,0,0,5\r\n");
port.writeBytes("T,1000,1\r\n");
}
catch (Exception e) {
System.out.println("start "+e.toString());
}
myThread.start();
}
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
System.out.println(st);
}
}
public static void main(String[] args) {
COM temp= new COM();
temp.start();
}
}
I have another class which is a frame containing a button and a JTextArea. This class is in communication with my first class COM.
When i click the button, COM is starting and show me the data in my Eclipse Console.
But now, I'd like to show it on my JTextArea.
How can I do it ?
Best regards,
Tofuw
Take a moment to read about this pattern.
Make the Thread a Subject. Before starting register the instance of the class that contains the JTextArea as the Observer with the instance of the Thread. At the run() instead of printing on the console, use the notify(String);
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
System.out.println(st);
}
}
Change to
public void run() {
System.out.println("lecture COM...");
for(;;){
String st = null;
try {
st=port.readLine();
} catch (IOException e) {System.out.println(e.getMessage());}
notifyObservers(st); //Pass the data to the observers.
}
}
EDIT:
I suppose you can rewrite the Thread to a simple class. It will render the program unresponsive while it reads, that's why you have a Thread. I suppose you can implement a cleaner way using Future<String>
public class GpsReader {
public class GenericGPSException extends Exception {
public GenericGPSException(String message, Throwable cause) {
super(message, cause);
}
}
public static void main(String[] args) {
// Example of usage
GpsReader gpsReader = new GpsReader();
String messageFromDevice;
try {
// Try read it
messageFromDevice = gpsReader.getCoordinate();
} catch (GenericGPSException e) {
// Error, what does it says?
messageFromDevice = e.getMessage();
}
JTextArea mockArea = new JTextArea();
// Show to user anything that comes to it.
mockArea.setText(messageFromDevice);
}
private boolean isReady;
private RandomAccessFile port;
public GpsReader() {
}
public String getCoordinate() throws GenericGPSException {
if (!isReady) {
try {
port = new RandomAccessFile("COM3", "rwd");
port.writeBytes("\r\n");
port.writeBytes("c,31,0,0,5\r\n");
port.writeBytes("T,1000,1\r\n");
isReady = true;
} catch (FileNotFoundException e) {
throw new GenericGPSException(
"Error at starting communication to Device ", e);
} catch (IOException e) {
throw new GenericGPSException(
"Error at starting communication to Device ", e);
}
}
try {
return port.readLine();
} catch (IOException e) {
throw new GenericGPSException("Error at reading the Device ", e);
}
}
}
First i run serveur_final.java,creating thread for clients,getting login and password from client and in the second thread verify them in database and after sending "ok" to client and initialize communication
public class Serveur_final {
private ServerSocket sock_serv=null;
private Socket client_entrant=null;
private static Vector<String> nom_client=null;
private static Vector<connect_serveur> list_client=null;
private int port=1991;
public Serveur_final() throws IOException{
initialisation();
}
public void initialisation() throws IOException {
sock_serv=new ServerSocket(port);
System.out.println("ecoute au"+port);
list_client=new Vector<connect_serveur>();
nom_client=new Vector<String>();
while(true){
client_entrant=sock_serv.accept();
connect_serveur con=new connect_serveur(client_entrant);
list_client.add(con) ;
}
}
public static void ajouter_list(String nom_cli){
nom_client.add(nom_cli);
diffusion_list(nom_client);
}
public static void supprimer_nom_client(String con){
for(String nom: nom_client){
if(nom.equals(con)){
nom_client.remove(nom);
}
}
}
public static void supprimer_client(connect_serveur con){
for(connect_serveur nom: list_client){
if(nom.equals(con)){
list_client.remove(nom);}
}
}
public static Vector<connect_serveur> getList_client(){
return list_client;
}
public static void diffusion_list(Vector<String> client) {
for(connect_serveur cl: list_client){
for(int i=0;i<client.size();i++){
cl.diffuser(nom_client.get(i));
}
}
}
public static void diffusion_message(String client,String message) {
for(connect_serveur cl: list_client){
/*for(int i=0;i<nom_client.size();i++){*/
cl.getThead_client().getEnvoi_msg().diffusion(client, message);
/*}*/
}
}
public static void deconnection(String pseudo) {
for(connect_serveur cl: list_client){
if(cl.getPseudo().equals(pseudo)){
list_client.remove(cl);
}
for(int i=0;i<nom_client.size();i++){
if(pseudo.equals(nom_client.get(i))){
nom_client.remove(i);
}
}
}
}
}
/
///class connect-serveur
public class connect_serveur extends Thread {
private Socket client;
private BufferedReader reception;
private static PrintWriter envoi;
private String pseudo,passwd;
/* private static Vector<String> list_nom_client;*/
initialisation_communication thread_client;
private boolean verif=false, autorisation=false;
public connect_serveur(Socket client_entrant) throws IOException {
this.client=client_entrant;
envoi=new PrintWriter(client.getOutputStream());
reception=new BufferedReader(new InputStreamReader(client.getInputStream()));
pseudo=reception.readLine();
passwd=reception.readLine();
verif=verifier_info(pseudo, passwd);
setPseudo(pseudo);
start();
}
#Override
public void run() {
try {
if(!verif){
envoi.println("bye4");
envoi.flush();
Serveur_final.supprimer_client(this);
reception.close();
envoi.close();
client.close();
Serveur_final.deconnection(pseudo);
}
envoi.println("ok");
envoi.flush();
Serveur_final.ajouter_list(pseudo);
thread_client=new initialisation_communication(pseudo, envoi,reception);
setThead_client(thread_client);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setPseudo(String pseudo2) {
this.pseudo=pseudo2;
}
public String getPseudo() {
return this.pseudo;
}
public initialisation_communication getThead_client(){
return thread_client;
}
public void setThead_client(initialisation_communication com ){
thread_client=com;
}
/*public static void diffuser_list(Vector<String>client){
list_nom_client=client;
for(int i=0;i<list_nom_client.size();i++){
diffuser(list_nom_client.get(i));
Serveur_final.diffusion_list();
}
}*/
public static void diffuser(String client) {
System.out.println("en diffusion");
envoi.println("0>>:"+client);
envoi.flush();
}
boolean verifier_info(String pseudo, String passwd) {
autorisation=connexion_bdd.getInstance().verification_log(pseudo, passwd);
System.out.println("AUTORISER"+autorisation);
if(autorisation)
{
envoi.println("ok");
envoi.flush();
System.out.println("adding user");
}
else {
envoi.println("no");
envoi.flush();
}
return autorisation;
}
}
//initialisation-comm class
public class initialisation_communication extends Thread {
private String pseudo;
private BufferedReader reception;
private PrintWriter envoi;
private envoyer_message envoi_msg;
private recevoir_message recoi_msg;
public initialisation_communication(String pseudo,PrintWriter envoi,BufferedReader reception) {
// TODO Auto-generated constructor stub
this.envoi=envoi;
this.reception=reception;
this.pseudo=pseudo;
start();
}
#Override
public void run() {
/*envoi=new PrintWriter(socket_client.getOutputStream());
BufferedReader reception = new BufferedReader(new InputStreamReader(socket_client.getInputStream()));*/
System.out.println("initialiser");
envoi_msg=new envoyer_message(pseudo,envoi,reception);
recoi_msg=new recevoir_message(reception);
setEnvoi_msg(envoi_msg);
}
public envoyer_message getEnvoi_msg(){
return envoi_msg;
}
public void setEnvoi_msg(envoyer_message com ){
this.envoi_msg=com;
}
}
//envoyer_msg class:from which i'm getting errors
public class envoyer_message extends Thread {
private PrintWriter emettre;
private BufferedReader reception;
private String pseudo;
public envoyer_message(String pseudo, PrintWriter envoi, BufferedReader reception) {
this.emettre=envoi;
this.reception=reception;
this.pseudo=pseudo;
System.out.println("dans envoyer dja");
start();
}
public void run(){
String message;
emettre.println("bien connectee");
try {
while (true) {
message = reception.readLine();
if(message=="!!>>fin<<!!"){
Serveur_final.deconnection(pseudo);
}
Serveur_final.diffusion_message(pseudo, message);
} // end of while
} // try
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public void diffusion(String pseudo2, String message) {
emettre.println(">>:"+pseudo2+"dit :"+message);
}
}
and finally my client
public class client_chat {
private Socket socket_client;
private String connected="",passwd,login,adress_server="localhost";
private int Port=1991;
private BufferedReader entrer=null;
private PrintWriter sortie=null;
private static client_chat client;
private boolean connecte=false;
private BufferedReader clavier ;
private String message;
private boolean fermer;
public client_chat(){
try {
this.socket_client=new Socket(adress_server,Port);
connecte=getConnection("nao", "nao");
init(connecte);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.getMessage();
}
}
public static client_chat getIntance(){
if(client==null){
client=new client_chat();
}
return client;
}
public boolean getConnection(String pseudo,String passwd){
this.login=pseudo;
this.passwd=passwd;
if(socket_client!=null){
try {
entrer=new BufferedReader(new InputStreamReader(socket_client.getInputStream()));
sortie=new PrintWriter(socket_client.getOutputStream());
sortie.println(pseudo);
sortie.flush();
sortie.println(passwd);
sortie.flush();
connected=entrer.readLine();
System.out.println(connected);
if(connected=="ok"){
connecte=true;
System.out.println(connected);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connecte;
}
public void init(Boolean con) throws IOException{
if(con ){
new ThreadLecture().start();
while(!fermer){
clavier=new BufferedReader(new InputStreamReader(System.in));
sortie.println(clavier.readLine());
}
entrer.close();
sortie.close();
socket_client.close();
}
}
public void setLogin(String ps){
this.login=ps;
}
public String getLogin(){
return this.login;
}
public void setPasswd(String ps){
this.passwd=ps;
}
public String getPasswd(){
return this.passwd;
}
class ThreadLecture extends Thread{
public void run() {
try {
System.out.println("dans runcli");
while(true){
message=entrer.readLine();
System.out.println(message);
if(message.indexOf("bye4")!=-1 ||message.indexOf ("!!>>fin<<!!")!=-1)
break;
enter code here
}
fermer=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
error message after running client_chat.java
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at modeles.envoyer_message.run(envoyer_message.java:30)
sorry for my english, I need your help please!
I have tried all the tips
"All the tips" say the same thing, or they should. You have written to a connection that had already been closed by the other end. An application protocol error.
There isn't nearly enough EOS-checking in your code either. For example you are just assuming you receive both the username and the password.
I don't know if this will fix this, but i noticed your check:
if(message=="!!>>fin<<!!"){
in envoyer_msg.run() is wrong.
message is a String, string comparison is done by equals()/compareTo().
Cheers
I have a somewhat simple server meaning that i am trying to learn different design patterns by making a server as object orientated as possible. Suprisingly so far i havnt had a single problem untill i created the method close().
apprently when a client closes his connection with the database the BufferReader still wants input and throws an execption saying that Java.net.socketExecption: socket closed
since i have alot of different classes i will only post the ones that are failing at the moment if you need additional information please do not hesitate to send me a comment. Also since i am trying to learn from this project please comment on my code aswell if you feel like it :)
Code (all of my code)
public class ServerConnectionManager {
private static ServerSocket server;
private static Socket connection;
private static ServerInformation ai = new ServerInformation();
private static boolean connected = false;
private static final int portNumber = 7070;
private static int backLog = 100;
/**
* This method launches the server (and the application)!
* #param args
*/
public static void main(String[] args){
startServer();
waitForConnection();
}
/**
*This method sets the serverSocket to portNumber and also adds the backLog.
*/
private static void startServer() {
try {
server = new ServerSocket(portNumber, backLog);
connected = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This method waits for a connection aslong as the serverSocket is connected.
* When a new client connects it creates an Object of the connection and starts the individual procedure.
*/
private static void waitForConnection() {
while (connected) {
try {
connection = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection c = new Connection(connection);
ai.addToConnectionList(c);
waitForConnection();
}
}
public void closeMe(Socket con) {
for (Connection conn : ai.getConnectionList()) {
if (conn.getConnection() == con) {
conn.close();
}
}
}
}
Connection
public class Connection{
private Socket connection;
public Connection(Socket connection){
this.connection = connection;
ServerListner cl = new ServerListner(Connection.this);
cl.start();
}
public Socket getConnection(){
return this.connection;
}
public void close() {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerListner
public class ServerListner extends Thread {
private Socket connection;
private BufferedReader br;
private ChatPerson person;
private Connection con;
private ServerInformation ai = new ServerInformation();
private ServerConnectionManager scm = new ServerConnectionManager();
private ServerSender sender = new ServerSender();
public ServerListner(Connection con){
this.con = con;
connection = con.getConnection();
try {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getConnection(){
return this.connection;
}
public void run(){
while (con.getConnection().isConnected()) {
String inString;
try {
while ((inString = br.readLine()) != null) {
processInput(inString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void processInput(String input){
if (input.equalsIgnoreCase("Connect")) {
sender.sendMessageToConnection(this.connection, "Accepted");
}
if (input.equalsIgnoreCase("UserInformation")) {
try {
String username = br.readLine();
person = new ChatPerson(username, connection);
ai.add(person);
System.out.println(ai.getList());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (input.equalsIgnoreCase("SearchByCon")) {
String name = ai.searchByConnection(connection);
System.out.println(name);
}
if (input.equals("Disconnect")) {
scm.closeMe(connection);
}
}
}
** Server Sender**
public class ServerSender {
private PrintWriter pw;
private ServerInformation ai = new ServerInformation();
public void addToList(){
}
public void sendToAll(String message){
for (Connection c : ai.getConnectionList()) {
try {
pw = new PrintWriter(c.getConnection().getOutputStream());
pw.print(message);
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
* #param con
* #param message
*/
/*
* Note - Denne metode gør også at jeg kan hviske til folk!:)
*/
public void sendMessageToConnection(Socket con, String message){
try {
PrintWriter print = new PrintWriter(con.getOutputStream());
print.println(message);
print.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
** Server Information**
public class ServerInformation {
private ArrayList<Connection> connectedClients = new ArrayList<Connection>();
private ArrayList<ChatPerson> list = new ArrayList<ChatPerson>();
public ArrayList<Connection> getConnectionList(){
return connectedClients;
}
public void addToConnectionList(Connection con){
connectedClients.add(con);
}
public String searchByConnection(Socket myConnection){
for (ChatPerson p : list) {
if (p.getConnection() == myConnection) {
return p.getName();
}
}
/*
* If none found!
*/
return null;
}
public void add(ChatPerson p){
list.add(p);
}
public void removeByName(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
list.remove(p);
}
}
}
public String searchList(String name){
for (ChatPerson p : list) {
if (p.getName().equalsIgnoreCase(name)) {
return p.getName();
}
}
return null;
}
public ArrayList<ChatPerson>getList(){
return list;
}
}
** ChatPerson**
public class ChatPerson {
private String chatName;
private Socket connection;
/*
* This is for furture development
* private Integer adminLevel;
*/
public ChatPerson(String name, Socket connection){
this.chatName = name;
this.connection = connection;
}
public void setName(String name){
this.chatName = name;
}
public String getName(){
return chatName;
}
public String toString(){
return "Username: "+chatName;
}
public Socket getConnection(){
return connection;
}
}
I have tried the following thing(s):
try {
String inString;
while ((inString = br.readLine()) != null) {
if (inString.equalsIgnoreCase("Disconnect")) {
System.out.println(inString);
break;
}else {
processInput(inString);
}
}
scm.closeMe(connection);
This did not work still gave me the same execption.
while (con.getConnection().isConnected()) {
String inString;
try {
while ((inString = br.readLine()) != null) {
processInput(inString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Having both these loops is meaningless. readLine() will return null as soon as EOS is reached, at which point you should close the socket and exit the loop. In any case isConnected() doesn't tell you anything about the state of the connection, only about which APIs you have called on your Socket which is the endpoint of it. Lose the outer loop.
The documentation on Socket says
Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.
You may want to break out of your readline() loop and close the connection outside of this.
class SomeUI
{
SocketMessageSender messageSender;
// ensure that its initialized ...
private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
messageSender.sendMessage(jMessage.getText());
jMessage.setText("");
} catch (IOException ex) {
Logger.getLogger(TeKServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ERROR: Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: bSendMessageActionPerformed
Why do you keep opening the socket and closing it on every button click. Create a class that allow you to keep the socket open for as long as your application run. The socket connection can be done when the application starts.You can try out the following class
public class SocketMessageSender
{
private String host;
private int port;
private DataOutputStream dos;
public SocketMessageSender(String host, int port)
{
this.host = host;
this.port = port;
}
// call when application starts
public void initConnection() throws IOException
{
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
dos = new DataOutputStream(connection.getOutputStream());
}
//call from button click
public void sendMessage(String message) throws IOException
{
if(dos != null)
{
dos.writeUTF(message);
dos.flush();
}
}
// call when application exits
public void closeConnection() throws IOException
{
if(dos!= null)
{
dos.close();
}
}
}
Hope it helps ...
Assume you have a class like
class SomeUI
{
SocketMessageSender messageSender;
// ensure that its initialized ...
private void bSendMessageActionPerformed(java.awt.event.ActionEvent evt) {
messageSender.sendMessage(jMessage.getText());
jMessage.setText("");
}
}
I think that the class signature should be something like this ....
public class MyPanel extends JPanel implements ActionListener
{
private SocketMessageSender messageSender;
private Message jMessage = new Message();// This is just a temp class, replace this with your class
public MyPanel()
{
messageSender = new SocketMessageSender("some host", 8080);
try
{
messageSender.initConnection();
}
catch(IOException e)
{
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, e);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
try {
// TODO add your handling code here:
messageSender.sendMessage(jMessage.getText());
jMessage.setText("");
} catch (IOException ex) {
Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Consider using ObjectOutputStream/ObjectInputStream and write object through sockets.
There are a lot of examples at java2s.com
Please mind that if you are writing same object multiple times, you will need to reset() stream before writing, and flush after it.