473,386 Members | 1,796 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

How do I close a UDP server without throwing an exception?

108 100+
I have a server that waits for incoming client messages and uses UDP. When I try to close the Udp connection I get an IOException..

Expand|Select|Wrap|Line Numbers
  1.  
  2. public void run(){
  3.  
  4.     String user_message = null;
  5.  
  6.     try {
  7.             connection = startServer();
  8.             System.out.println("Server started");
  9.             while ((true) && (serverStarted) ){
  10.  
  11.                     try {
  12.  
  13.  
  14.                             user_message = receiveMessage();
  15.                             check_query( user_message , "," );
  16.  
  17.                     } catch ( IOException ex ) {
  18.                             System.out.println("Error1 "+ex.getMessage());
  19.                             setError( "Error establishing connection " ) ;
  20.                             Txt_Log.setText(Txt_Log.getText() + "\n Error establishing connection0") ;
  21.                             break;
  22.                         }
  23.                 }
  24.             System.out.println("Server is stopped.....");
  25.         }
  26.     catch ( SocketException ex ) {
  27.             System.out.println("Error2 "+ex.getMessage());
  28.             setError("Error establishing connection ") ;
  29.             Txt_Log.setText(Txt_Log.getText() + "\n Error establishing connection1") ;
  30.  
  31.        }
  32.     catch( NullPointerException ex){
  33.             System.out.println("Error3 "+ex.getMessage());
  34.             ex.printStackTrace();
  35.             setError("Error Null Pointer ") ;
  36.             Txt_Log.setText(Txt_Log.getText() + "\n Error :"+ex.getMessage()) ;
  37.     }
  38. }
  39.  
  40.  
  41.  
  42.  
  43.  
  44. /*
  45.  * Method starts server datagram to bind to port
  46.  */
  47.  
  48. public DatagramSocket startServer() throws SocketException{
  49.  
  50.             return new DatagramSocket(10000);
  51. }
  52.  
  53.  
  54.  
  55.  
  56. /*
  57.  * Method stops server so that server is not able to receive client requests
  58.  */
  59.  
  60. public void closeServer(){
  61.  
  62.         if (connection != null){
  63.                 //connection.disconnect();
  64.                 connection.close();
  65.                 //connection = null;
  66.  
  67.         }
  68. }
  69.  
  70.  
  71.  
  72. /*
  73.  * Method sends message via datagram to client
  74.  */
  75.  
  76. private void sendMessage( String message ) throws IOException{
  77.  
  78.         byte[] message_byte = message.getBytes();
  79.         packet_send = new DatagramPacket( message_byte , message_byte.length , packet_receive.getAddress() , packet_receive.getPort() );
  80.         connection.send( packet_send );
  81. }
  82.  
  83.  
  84.  
  85.  
  86. /*
  87.  * Method receives messages from clients
  88.  */
  89. private String receiveMessage() throws IOException,NullPointerException{
  90.     if (connection!=null){
  91.         byte[] buf = new byte[256];
  92.         packet_receive = new DatagramPacket( buf , buf.length ) ;
  93.         connection.receive( packet_receive ) ;
  94.         return getString( packet_receive );
  95.     }
  96.     throw new NullPointerException("Connection cannot be null");
  97. }
  98.  
  99.  
  100.  
  101. /*
  102.  * Method retrieves data from packet and converts to string
  103.  */
  104.  
  105. private String getString(DatagramPacket packet){
  106.  
  107.         String string = new String ( packet.getData() , 0 , packet.getLength()).trim();
  108.         return string;
  109. }
  110.  
  111. private void drop_DBconnection(){ if (DB_connection!=null){ try{ DB_connection.close(); //DB_connection = null;
  112.  
  113.             }
  114.         catch(SQLException e){
  115.  
  116.                 Txt_Log.setText("Server connection Error...");
  117.                 setError("Cannot close database connection");
  118.             }
  119.  
  120.         }
  121. }
  122.  
  123. public void closeServer(){
  124.  
  125.         if (connection != null){
  126.                 //connection.disconnect();
  127.                 connection.close();
  128.                 //connection = null;
  129.  
  130.         }
  131. }
  132.  
  133.  
  134.  
My output and stacktrace

Server started Server is started..... Error1 socket closed Server is stopped..... java.net.SocketException: socket closed at java.net.PlainDatagramSocketImpl.receive0(Native Method) at java.net.PlainDatagramSocketImpl.receive(PlainData gramSocketImpl.java:136) at java.net.DatagramSocket.receive(DatagramSocket.jav a:712) at server.Server.receiveMessage(Server.java:608) at server.Server.run(Server.java:528) at java.lang.Thread.run(Thread.java:619)

How do I close the server so that no exception is thrown?
Feb 9 '11 #1
2 2910
horace1
1,510 Expert 1GB
where do you call closeServer()
I suggest you need to terminate the run() method when the server is closed, e.g. possibly some test here to ensure the server is still running ?
Expand|Select|Wrap|Line Numbers
  1.        while ((true) && (serverStarted) ){
  2.  
Feb 9 '11 #2
Dheeraj Joshi
1,123 Expert 1GB
I am not sure how closeServer methos is working in your project.
Better to add some intelligence to closeserver method and what it returns.

Depending on the output you can continue your operation.

Regards
Dheeraj Joshi
Feb 14 '11 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Hank | last post by:
Please help me diagnose the following problem. I have a Swing program (running under 1.4.2_04) that uses JNI to get some hardware-level information and return that info as a csv String. The...
2
by: Jacques Koorts | last post by:
Hi, I've managed to get the parent window close the child window (popup). I do this by the child calling the parent to close it. How can the child close itself without help from parent? So...
40
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
5
by: KJ | last post by:
This is kind of hard to explain but I have a The controls are created with CreateChildControls(). Now let say I click a button and an error occurs in the control. If I throw it up it goes back...
0
by: ruca | last post by:
Hi, It's that... It gives me an error "The server threw an exception" when my WebApplication try's to interop with a Dll, calling a function of this dll. The WebApllication is running under...
10
by: mttc | last post by:
I read articles that suggest preventing delete by throwing Exception from RowDeleting Event. I not understand where I can catch this Error?
1
by: problemKing | last post by:
Hi all, I had created a Remoting Custom Exception that inherits from System.Exception. Now, i meet the same problem that has been posted by previous thread...
1
by: tamasumalta | last post by:
I am using the attached code Private Sub StartApplicationProcess InitialiseObject() oWord.Visible = True oDoc = oWord.Documents.Open(StrStackPath) oWord.Visible = True end sub The...
3
by: Deivys Ramirez | last post by:
Hi everyone, I'm a Python newbie but have experience programming PHP and C so i'm not really new to programming but new to Python. What's the "pythonic" way of reading a text file, line by...
5
by: nikhilkajrekar | last post by:
For Each objObj In .CurrentProject.AllForms DoEvents intObj = intObj + 1 .DoCmd.OpenForm objObj.Name, acDesign, , , , acHidden Set objForm = .Forms(objObj.Name) With...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.