473,805 Members | 1,887 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Client Server application code

1 New Member
Hello!I am new in this site and wish to improve my java clent server application code.It's to connect the client to the server through a port and random jokes request by the client to the server be sent to the client.

Thanks
Oct 28 '06 #1
1 4336
horace1
1,510 Recognized Expert Top Contributor
a simple server which waits for message from a client
Expand|Select|Wrap|Line Numbers
  1. // server which waits for messages from a client
  2. import java.io.*;
  3. import java.util.*;
  4. import java.net.*;
  5.  
  6.  
  7. public class TCPserver extends Thread
  8. {
  9.         private ServerSocket   serverSocket;
  10.         ObjectInputStream br=null;
  11.         ObjectOutputStream pw=null;
  12.         int receivePort;                // port to receive  from
  13.         boolean threadRunning = true;   // flag to terminate thread
  14.  
  15.         TCPserver(int receivePort)    // constructor to receive datagrams on port receivePort
  16.     {
  17.                 this.receivePort = receivePort;
  18.     }
  19.  
  20.         // terminate the thread by setting flag
  21.         public void stopTCPserver()
  22.         {
  23.                 threadRunning = false;
  24.         }
  25.  
  26.         public void run()                // thread run method, receives and buffers datagrams
  27.         {
  28.           Socket socket=null;
  29.           try
  30.               {
  31.               while (threadRunning)
  32.               {
  33.                   System.out.println("TCP server starting: IP address " 
  34.                        + InetAddress.getLocalHost().toString() + " port " + receivePort );
  35.                   serverSocket = new ServerSocket(receivePort);
  36.                   socket = serverSocket.accept(); // Wait for client to connect.
  37.                   System.out.println("Client connect from IP address " + socket.getInetAddress()
  38.                                   + " port " + socket.getPort());
  39.                   br  = new ObjectInputStream( ( socket.getInputStream() ) );
  40.                   pw = new ObjectOutputStream( socket.getOutputStream() );
  41.                   while(threadRunning)
  42.                     try
  43.                     {
  44.                       String code = (String) br.readObject();
  45.                       System.out.println( "Server received string: '" + code + "'");
  46.                     }
  47.                     catch (Exception se) {System.err.println("done"); break;}
  48.                   serverSocket.close();
  49.                 }
  50.               }
  51.           catch (Exception se) {System.err.println("run() " + se); }
  52.  
  53.           System.exit(1);                                                 // exit on failure
  54.         }
  55.  
  56.  
  57. public static void main(String args[])
  58. {
  59.         int receivePort=9000;                                 // port to receive datagrams on
  60.         TCPserver frameInput = new TCPserver(receivePort);    // create server to receive messages
  61.         frameInput.start();                                   // and start it
  62.         System.out.println("ready to receive datagrams from socket " + receivePort);
  63.         }
  64.  
  65. }
  66.  
  67.  
a simple client which sends messages entered at keyboard to the server
Expand|Select|Wrap|Line Numbers
  1. // client which sends a message to a server using TCP
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5. import java.net.*;
  6.  
  7. public class TCPclient
  8. {
  9.  
  10.         static void sendString(String remoteIPaddress, int remotePort)
  11.         {
  12.         Socket         socket1;        // To server.
  13.         ObjectOutputStream        objOut;        // To write to server.
  14.                 try
  15.                 {
  16.                  socket1 = new Socket( remoteIPaddress, remotePort );   
  17.                  objOut = new ObjectOutputStream( socket1.getOutputStream() );
  18.                  System.out.println("Server contacted OK sending " );
  19.                  while(true)
  20.                    {
  21.                      String s = in.readLine();
  22.                      objOut.writeObject(s);         // send message three times
  23.                    }  // end try
  24.                 }
  25.                 catch (UnknownHostException e) {System.err.println("SendString " +  e); }
  26.                 catch (SocketException se) {System.err.println("SendString " +  se); }
  27.                 catch (IOException e) {System.err.println("SendString " +  e); }
  28.         }
  29.  
  30.   private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  31. public static void main(String args[])
  32. {
  33.    System.out.println("enter message to send to server");
  34.    TCPclient.sendString("127.0.0.1", 9000);
  35. }
  36.  
  37. }
  38.  
1. compile the server and run it
2. compile the client and run it
3. message typed in a client appear at server
Nov 1 '06 #2

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

Similar topics

5
2578
by: Matt | last post by:
I think this is the basic concept in ASP server-side development. My boss told me web application is NOT client-server application. I argued with him because browser is the client, and the server code put in server. Then web application should be a client-server application. My understanding is that a web application is an application that runs on a browser. But client-server application is not necessary a web application. Please...
2
2418
by: Microsoft | last post by:
I'm about to start converting my application from a old-style monolith exe (with flat files and limited database support for sharing some of the data) to a layered .NET SQL server version. I have decided to do it as a Windows Forms client application, hooking up to a central SQL Server, and then maybe later create an asp version of the client if needed. I have a couple of questions on the setup: 1) The clients will be going through the...
18
7391
by: cjl | last post by:
Hey all: I know that it is silly in the age of Google to 'lose' something on the internet, but I recently checked out a project that had implemented a database with a subset of SQL in pure client-side javascript. I forgot to bookmark it, and now I can't find it. Anyone?
4
6598
by: Prince Kumar | last post by:
I joined a company recently and they have a java program which hangs (does nothing) after a while. This is no way consistent. It could succeed quite a few times and can fail a few other times. There is no consistency when it fails. Could anyone here shed some light on how to debug/resolve the issue. I guess IBM looked at the issue and were not able to pinpoint where the issue is. When the program hangs and when force the DB2...
6
3746
by: Ken Allen | last post by:
I am relatively new to .Net and C#, but I hav ebeen programing in other languages and done some COM work for a number of years. I am attempting to understand how to map an older program architecture into .Net -- not looking to do it at this time, just to understand how I would achieve it. In the old environment, we had two classes, a client and a server class, that managed a data object. The server object knew how to interface with the...
10
2059
by: Ben | last post by:
Hi, I made an application in classic asp (reservation of books and video stuffs for students) and want to migrate to asp.net. The user has to chose a date, then pushung on a submit button. The whole day is then displayed in cels of a table. The user has then to click in a cel representing a hour of the day and an object (book ..), and finally click on the submit button to insert that reservation in the database. My problem is: there...
22
6294
by: Jordan S. | last post by:
SQL Server will be used as the back-end database to a non trivial client application. In question is the choice of client application: I need to be able to speak intelligently about when one client (MS Access vs ..NET Windows Forms) would be preferred over the other. While I have some good arguments on both sides, I would appreciate your points of view on the topic.
13
31437
by: =?Utf-8?B?S2VzdGZpZWxk?= | last post by:
Hi Our company has a .Net web service that, when called via asp.net web pages across our network works 100%! The problem is that when we try and call the web service from a remote machine, one outside of our domain, we get the error.. ** Client found response content type of 'text/html; charset=Windows-1252', but expected 'text/xml' **. We can discover the web service by typing in the url of the asmx so we know the server can 'see' it...
2
4730
by: Wimpie van Lingen | last post by:
Hey I have some more questions with regards to Remoting in .NET 2. I'm using TCP with the Binary formatter. My solution consists of 4 projects: - Class Library containing the server classes which Inherits MarshalByRefObject (ok, at this stage it only contains one class... but its gonna grow) - Class Library containing common classes and interfaces that will be shared between all projects. This include interfaces for the server...
0
9596
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10360
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10366
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10105
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5542
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.