Results 1 to 13 of 13
Thread: Server Socket GUI Freezes
- 09-29-2011, 02:14 PM #1
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Server Socket GUI Freezes
Hello there i have a server/client socket program an i decided i needed a gui for the server side i made a basic gui with a start and stop jbutton but soon as i press start the program runs fine but then i cant stop it ? here is code::
GUI:
Java Code:import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ServerInterFace extends JFrame{ JButton button,stbutton; EchoServer server; Container c; handler handle; public ServerInterFace(){ super("Login form"); handle =new handler(); c=getContentPane(); c.setLayout(new FlowLayout()); //extra classes handle =new handler(); button=new JButton("Start"); stbutton=new JButton("Stop"); //adding actionlistener to the button button.addActionListener(handle); stbutton.addActionListener(handle); c.add(button); c.add(stbutton); //visual setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(200,130); } class handler implements ActionListener { //must implement method //This is triggered whenever the user clicks the login button public void actionPerformed(ActionEvent ae) { //checks if the button clicked if(ae.getSource()==button) { EchoServer server = new EchoServer(); }else if(ae.getSource()==stbutton){ server.stopserver(); server=null; } }//method }//inner class } SERVER: import java.net.*; import java.io.*; import javax.swing.*; public class EchoServer { ServerSocket m_ServerSocket; Mysql db; public boolean stopped = false; public EchoServer() { db=new Mysql(); try { // Create the server socket. m_ServerSocket = new ServerSocket(12111); } catch(IOException ioe) { System.out.println("Could not create server socket at 12111. Quitting."); System.exit(-1); } System.out.println("Listening for clients on 12111"); // Successfully created Server Socket. Now wait for connections. int id = 0; while(true) { try { // Accept incoming connections. Socket clientSocket = m_ServerSocket.accept(); // accept() will block until a client connects to the server. // If execution reaches this point, then it means that a client // socket has been accepted. // For each client, we will start a service thread to // service the client requests. This is to demonstrate a // multithreaded server, although not required for such a // trivial application. Starting a thread also lets our // EchoServer accept multiple connections simultaneously. // Start a service thread ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++); cliThread.start(); } catch(IOException ioe) { System.out.println("Exception encountered on accept. Ignoring. Stack Trace :"); ioe.printStackTrace(); } } } public void stopserver(){ m_ServerSocket = null; System.exit(-1); } public static void main (String[] args) { new EchoServer(); } class ClientServiceThread extends Thread { Socket m_clientSocket; int m_clientID = -1; boolean m_bRunThread = true; ClientServiceThread(Socket s, int clientID) { m_clientSocket = s; m_clientID = clientID; } public void run() { SwingUtilities.invokeLater(this); // Obtain the input stream and the output stream for the socket // A good practice is to encapsulate them with a BufferedReader // and a PrintWriter as shown below. BufferedReader in = null; PrintWriter out = null; // Print out details of this connection System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + m_clientSocket.getInetAddress().getHostName()); try { in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream())); out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); // At this point, we can read for input and reply with appropriate output. // Run in a loop until m_bRunThread is set to false while(m_bRunThread && in!=null) { // read incoming stream String clientCommand = in.readLine(); String[] msg = clientCommand.split(","); String temp_cmd1 = msg[0]; String[] temp_cmd2 = temp_cmd1.split("="); String cmd = temp_cmd2[1]; if(cmd.equalsIgnoreCase("quit")) { // Special command. Quit this thread m_bRunThread = false; System.out.print("Stopping client thread for client : " + m_clientID); } if(cmd.equalsIgnoreCase("login")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_uname = msg[1].split("="); String uname = temp_uname[1]; String[] temp_pass = msg[2].split("="); String pwd = temp_pass[1]; //out.println(uname+":"+pass); //out.flush(); int taskman = db.loginplayer(uname,pwd); if(taskman>0){ out.println("cmd=loginsuc,pid=1"); out.flush(); }else{ out.println("cmd=loginfail"); out.flush(); } } if(cmd.equalsIgnoreCase("logout")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); db.logoutuser(playerid); } if(cmd.equalsIgnoreCase("getplayerdata")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); out.println(db.getplayerdata(playerid)); out.flush(); } if(cmd.equalsIgnoreCase("updateppos")){ String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); String[] temp_xpos = msg[2].split("="); int xpos = Integer.parseInt(temp_xpos[1]); String[] temp_ypos = msg[3].split("="); int ypos = Integer.parseInt(temp_ypos[1]); db.updateplayerpos(xpos,ypos,playerid); } } } catch(Exception e) { //e.printStackTrace(); } finally { // Clean up try { in.close(); out.close(); m_bRunThread=false; m_clientSocket.close(); System.out.println("Client : ID - " + m_clientID +"...Stopped"); } catch(IOException ioe) { ioe.printStackTrace(); } } } } }
Last edited by Norm; 09-29-2011 at 03:10 PM. Reason: added code tags
-
Re: Server Socket GUI Freezes
You will want to read/study this tutorial on Concurrency in Swing. It will explain what your problem is, and how to fix it.
- 09-29-2011, 04:32 PM #3
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Re: Server Socket GUI Freezes
ok i have read through the thing you sent me but still cant work out how to solve my problem?!
- 09-29-2011, 05:31 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 13,541
- Rep Power
- 27
Re: Server Socket GUI Freezes
Inside your action listener you do:
Java Code:EchoServer server = new EchoServer();
All of this is done on the EDT (the Swing thread).
This means no other events can ever be run...hence you lock up.
So read the tutorial Fubarable posted and try to understand how to deal with this sort of thing in your app.
- 09-29-2011, 05:43 PM #5
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Re: Server Socket GUI Freezes
Ok so i have read the tutorial again but still dont understand what to do to make it work
-
Re: Server Socket GUI Freezes
Last edited by Fubarable; 09-29-2011 at 08:20 PM.
- 09-30-2011, 11:27 AM #7
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Re: Server Socket GUI Freezes
I know i have to use a swingworker but i just dont know where to put it in my code
SERVER:
Java Code:import java.net.*; import java.io.*; import javax.swing.*; public class EchoServer extends Thread { ServerSocket m_ServerSocket; Mysql db; public boolean stopped = false; public EchoServer() { db=new Mysql(); try { // Create the server socket. m_ServerSocket = new ServerSocket(12111); } catch(IOException ioe) { System.out.println("Could not create server socket at 12111. Quitting."); System.exit(-1); } System.out.println("Listening for clients on 12111"); // Successfully created Server Socket. Now wait for connections. SwingUtilities.invokeLater(new Runnable() { public void run() { int id = 0; try{ while(stopped!=true) { try { // Accept incoming connections. Socket clientSocket = m_ServerSocket.accept(); // accept() will block until a client connects to the server. // If execution reaches this point, then it means that a client // socket has been accepted. // For each client, we will start a service thread to // service the client requests. This is to demonstrate a // multithreaded server, although not required for such a // trivial application. Starting a thread also lets our // EchoServer accept multiple connections simultaneously. // Start a service thread ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++); cliThread.start(); } catch(IOException ioe) { System.out.println("Exception encountered on accept. Ignoring. Stack Trace :"); ioe.printStackTrace(); } } }catch(Exception e){ } } }); return; } public void stopserver(){ m_ServerSocket = null; System.exit(-1); } public static void main (String[] args) { new EchoServer(); } class ClientServiceThread extends Thread { Socket m_clientSocket; int m_clientID = -1; boolean m_bRunThread = true; ClientServiceThread(Socket s, int clientID) { m_clientSocket = s; m_clientID = clientID; } public void run() { // Obtain the input stream and the output stream for the socket // A good practice is to encapsulate them with a BufferedReader // and a PrintWriter as shown below. BufferedReader in = null; PrintWriter out = null; // Print out details of this connection System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + m_clientSocket.getInetAddress().getHostName()); try { in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream())); out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); // At this point, we can read for input and reply with appropriate output. // Run in a loop until m_bRunThread is set to false while(m_bRunThread && in!=null) { // read incoming stream String clientCommand = in.readLine(); String[] msg = clientCommand.split(","); String temp_cmd1 = msg[0]; String[] temp_cmd2 = temp_cmd1.split("="); String cmd = temp_cmd2[1]; if(cmd.equalsIgnoreCase("quit")) { // Special command. Quit this thread m_bRunThread = false; System.out.print("Stopping client thread for client : " + m_clientID); } if(cmd.equalsIgnoreCase("login")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_uname = msg[1].split("="); String uname = temp_uname[1]; String[] temp_pass = msg[2].split("="); String pwd = temp_pass[1]; //out.println(uname+":"+pass); //out.flush(); int taskman = db.loginplayer(uname,pwd); if(taskman>0){ out.println("cmd=loginsuc,pid=1"); out.flush(); }else{ out.println("cmd=loginfail"); out.flush(); } } if(cmd.equalsIgnoreCase("logout")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); db.logoutuser(playerid); } if(cmd.equalsIgnoreCase("getplayerdata")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); out.println(db.getplayerdata(playerid)); out.flush(); } if(cmd.equalsIgnoreCase("updateppos")){ String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); String[] temp_xpos = msg[2].split("="); int xpos = Integer.parseInt(temp_xpos[1]); String[] temp_ypos = msg[3].split("="); int ypos = Integer.parseInt(temp_ypos[1]); db.updateplayerpos(xpos,ypos,playerid); } } } catch(Exception e) { //e.printStackTrace(); } finally { // Clean up try { in.close(); out.close(); m_bRunThread=false; m_clientSocket.close(); System.out.println("Client : ID - " + m_clientID +"...Stopped"); } catch(IOException ioe) { ioe.printStackTrace(); } } } } }
Java Code:import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ServerInterFace extends JFrame{ JButton button,stbutton; JTextArea textArea; EchoServer server; Container c; handler handle; public ServerInterFace(){ super("Login form"); handle =new handler(); c=getContentPane(); c.setLayout(new FlowLayout()); //extra classes handle =new handler(); textArea = new JTextArea(); textArea.setPreferredSize(new Dimension(170,100)); textArea.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black)); textArea.append("Hello"); JScrollPane scrollPane = new JScrollPane(textArea); textArea.setEditable(false); button=new JButton("Start"); stbutton=new JButton("Stop"); //adding actionlistener to the button button.addActionListener(handle); stbutton.addActionListener(handle); c.add(textArea); c.add(button); c.add(stbutton); //visual setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(200,200); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { //Note 1 public void run() { ServerInterFace window = new ServerInterFace(); window.setVisible(true); } }); } class handler implements ActionListener { //must implement method //This is triggered whenever the user clicks the login button public void actionPerformed(ActionEvent ae) { //checks if the button clicked if(ae.getSource()==button) { try{ EchoServer server = new EchoServer(); }catch(Exception e){ System.out.println(e); } }else if(ae.getSource()==stbutton){ server.stopserver(); server=null; } }//method }//inner class }
- 09-30-2011, 03:34 PM #8
Re: Server Socket GUI Freezes
where to put it in my code
You can either change the constructor so that it starts its code on a new thread and returns
Or change the call to the constructor to be in a new thread.
You want the listener to return after calling the EchoServer's constructor.
- 09-30-2011, 05:19 PM #9
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Re: Server Socket GUI Freezes
ok so how do i go about doing
change the constructor so that it starts its code on a new thread and returns
- 09-30-2011, 05:23 PM #10
Re: Server Socket GUI Freezes
In the constructor create a thread with a run method that calls a method that does what the code in the current constructor does, start the thread and exit from the constructor. The thread will then execute what the constructor used to do.
- 09-30-2011, 05:28 PM #11
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Re: Server Socket GUI Freezes
i know this might sound a bit weird but do u think u can write it because i am very new to threads and sockets
- 09-30-2011, 05:29 PM #12
Re: Server Socket GUI Freezes
Try writing a very small simple program that creates and starts a Thread. Have that thread's run method print out a message to show it that it executed.
Search on the forum for lots of sample code.
- 09-30-2011, 05:39 PM #13
Member
- Join Date
- Sep 2011
- Posts
- 37
- Rep Power
- 0
Re: Server Socket GUI Freezes
YAY got it to work :) here is final code::
GUI:
Java Code:import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ServerInterFace extends JFrame{ JButton button,stbutton; JTextArea textArea; EchoServer server; Container c; handler handle; public ServerInterFace(){ super("Login form"); handle =new handler(); c=getContentPane(); c.setLayout(new FlowLayout()); //extra classes handle =new handler(); textArea = new JTextArea(); textArea.setPreferredSize(new Dimension(170,100)); textArea.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black)); textArea.append("Hello"); JScrollPane scrollPane = new JScrollPane(textArea); textArea.setEditable(false); button=new JButton("Start"); stbutton=new JButton("Stop"); //adding actionlistener to the button button.addActionListener(handle); stbutton.addActionListener(handle); c.add(textArea); c.add(button); c.add(stbutton); //visual setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(200,200); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { //Note 1 public void run() { ServerInterFace window = new ServerInterFace(); window.setVisible(true); } }); } class handler implements ActionListener { //must implement method //This is triggered whenever the user clicks the login button public void actionPerformed(ActionEvent ae) { EchoServer server = new EchoServer(); //checks if the button clicked if(ae.getSource()==button) { try{ server.start(); }catch(Exception e){ System.out.println(e); } }else if(ae.getSource()==stbutton){ server.stopserver(); } }//method }//inner class }
Java Code:import java.net.*; import java.io.*; import javax.swing.*; public class EchoServer extends Thread { ServerSocket m_ServerSocket; Mysql db; public boolean stopped = false; public void run() { startserver(); return; } public void startserver(){ db=new Mysql(); try { // Create the server socket. m_ServerSocket = new ServerSocket(12111); } catch(IOException ioe) { System.out.println("Could not create server socket at 12111. Quitting."); System.exit(-1); } System.out.println("Listening for clients on 12111"); int id = 0; while(stopped!=true) { try { // Accept incoming connections. Socket clientSocket = m_ServerSocket.accept(); // accept() will block until a client connects to the server. // If execution reaches this point, then it means that a client // socket has been accepted. // For each client, we will start a service thread to // service the client requests. This is to demonstrate a // multithreaded server, although not required for such a // trivial application. Starting a thread also lets our // EchoServer accept multiple connections simultaneously. // Start a service thread ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++); cliThread.start(); } catch(IOException ioe) { System.out.println("Exception encountered on accept. Ignoring. Stack Trace :"); ioe.printStackTrace(); } } } public void stopserver(){ stopped = true; m_ServerSocket = null; System.exit(-1); } public static void main (String[] args) { new EchoServer(); } class ClientServiceThread extends Thread { Socket m_clientSocket; int m_clientID = -1; boolean m_bRunThread = true; ClientServiceThread(Socket s, int clientID) { m_clientSocket = s; m_clientID = clientID; } public void run() { // Obtain the input stream and the output stream for the socket // A good practice is to encapsulate them with a BufferedReader // and a PrintWriter as shown below. BufferedReader in = null; PrintWriter out = null; // Print out details of this connection System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + m_clientSocket.getInetAddress().getHostName()); try { in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream())); out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); // At this point, we can read for input and reply with appropriate output. // Run in a loop until m_bRunThread is set to false while(m_bRunThread && in!=null) { // read incoming stream String clientCommand = in.readLine(); String[] msg = clientCommand.split(","); String temp_cmd1 = msg[0]; String[] temp_cmd2 = temp_cmd1.split("="); String cmd = temp_cmd2[1]; if(cmd.equalsIgnoreCase("quit")) { // Special command. Quit this thread m_bRunThread = false; System.out.print("Stopping client thread for client : " + m_clientID); } if(cmd.equalsIgnoreCase("login")){ String[] temp_uname = msg[1].split("="); String uname = temp_uname[1]; String[] temp_pass = msg[2].split("="); String pwd = temp_pass[1]; //out.println(uname+":"+pass); //out.flush(); System.out.println("Client " + m_clientID +" Says :" + cmd+" user:"+uname); int taskman = db.loginplayer(uname,pwd); if(taskman>0){ out.println("cmd=loginsuc,pid=1"); out.flush(); }else{ out.println("cmd=loginfail"); out.flush(); } } if(cmd.equalsIgnoreCase("logout")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); db.logoutuser(playerid); } if(cmd.equalsIgnoreCase("getplayerdata")){ System.out.println("Client " + m_clientID +" Says :" + cmd); String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); out.println(db.getplayerdata(playerid)); out.flush(); } if(cmd.equalsIgnoreCase("updateppos")){ String[] temp_pid = msg[1].split("="); int playerid = Integer.parseInt(temp_pid[1]); String[] temp_xpos = msg[2].split("="); int xpos = Integer.parseInt(temp_xpos[1]); String[] temp_ypos = msg[3].split("="); int ypos = Integer.parseInt(temp_ypos[1]); db.updateplayerpos(xpos,ypos,playerid); } } } catch(Exception e) { //e.printStackTrace(); } finally { // Clean up try { in.close(); out.close(); m_bRunThread=false; m_clientSocket.close(); System.out.println(" Client : ID - " + m_clientID +"...Stopped"); } catch(IOException ioe) { ioe.printStackTrace(); } } } } }
Similar Threads
-
Socket HTTP-Server
By MichaelH in forum NetworkingReplies: 6Last Post: 05-06-2011, 09:45 PM -
non-blocking SSL socket server
By e_scape in forum NetworkingReplies: 0Last Post: 04-12-2011, 06:18 PM -
events on a server socket
By newbiejava in forum New To JavaReplies: 13Last Post: 08-03-2010, 09:24 AM -
Server Socket
By Moncleared in forum New To JavaReplies: 1Last Post: 09-05-2009, 07:08 AM
Bookmarks