how to find tomcat server system information using java code? - java

i am developing web application and i host it in tomcat server. my requirement is client system wants to know the ip address of the system where the tomcat server located in a network.Before make any request to the server using java.or any possible to set default ip address for the tomcat server.and how can i use the default ip address to make a request if system ip and tomcat ip are different.

I don't know if I understood your question right. So the server is running in a local area network and your client software does not know which address/ip to connect to? You could add a multicast server to your servers app and a multicast receiver to your clients. The server will send a boardcast packet frequently to a specified boardcast address/channel, i.e. 203.0.113.0.
Once your client starts, it will receive the boardcast packet send by the server, as long as he is connected to the same channel. The packet is containing the servers address. You can than use that address to connect to the server.
Update
This is a very simplyfied example of a sender, receiver and a constants class to share the settings. It sends a String (Server is here) as packet data, but in a real world application, you should create an object serialize it at the server and deserialize it at the client. That object could hold more information about the server an could be verified at client side.
Server/Client side shared code:
public final class MulticastConstants {
public static final String MULTICAST_PACKET_DATA = "Server is here!";
public static final String MULTICAST_CHANNEL = "230.0.0.1";
public static final int MULTICAST_PORT = 8881;
public static final int MULTICAST_PACKET_SIZE = MULTICAST_PACKET_DATA.getBytes().length;
}
Server Side code:
The sender is a WebListener and will start and stop with your application.
#WebListener
public class MulticastSender implements ServletContextListener {
private MulticastSocket socket;
private boolean running = true;
private Thread mcss;
public MulticastSender() {
System.out.println("New " + this.getClass().getSimpleName());
try {
socket = new MulticastSocket(MulticastConstants.MULTICAST_PORT);
mcss = new MulticastServerThread();
} catch (IOException e) {
System.out.println("Error creating MulticastSender: " + e.getMessage());
}
}
#Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Starting " + this.getClass().getSimpleName());
mcss.start();
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("Stopping " + this.getClass().getSimpleName());
this.running = false;
socket.disconnect();
socket.close();
}
private class MulticastServerThread extends Thread {
public MulticastServerThread() {
super("MulticastServer");
}
public void run() {
System.out.println("Start sending multicast packets ...");
while (running) {
System.out.println("Sending multicast packet ...");
try {
byte[] dataBuffer = MulticastConstants.MULTICAST_PACKET_DATA.getBytes();
InetAddress group = InetAddress.getByName(MulticastConstants.MULTICAST_CHANNEL);
DatagramPacket packet = new DatagramPacket(dataBuffer, dataBuffer.length, group, MulticastConstants.MULTICAST_PORT);
socket.send(packet);
System.out.println("Packet send ...");
try {
sleep(2000);
} catch (InterruptedException e) {
}
} catch (IOException e) {
System.out.println("Error sending multicast packet: " + e.getMessage());
running = false;
break;
}
}
socket.close();
}
}
}
Client side code:
The client only receives a single packet for simplicity. You might create a thread to not to freeze your clients gui.
public class MulticastReceiver {
private MulticastSocket socket;
private InetAddress address;
public static void main(String[] args) throws InterruptedException {
new MulticastReceiver();
}
public MulticastReceiver() {
System.out.println("Starting MulticastReceiver ...");
try {
address = InetAddress.getByName(MulticastConstants.MULTICAST_CHANNEL);
socket = new MulticastSocket(MulticastConstants.MULTICAST_PORT);
socket.joinGroup(address);
DatagramPacket packet;
try {
byte[] buf = new byte[MulticastConstants.MULTICAST_PACKET_SIZE];
packet = new DatagramPacket(buf, buf.length);
System.out.println("Waiting for packets ...");
socket.receive(packet);
System.out.println("Received a packet (" + packet.getLength() + " bytes) ...");
// deserialize packet.getData() to your own object (for simplicity a String is used) ...
// check if type and serialVersionId are ok, otherwise dispose packet ...
System.out.println("Server is located at: " + packet.getAddress());
socket.close();
// connect to server ...
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (UnknownHostException e) {
System.out.println("Could not connect to host \"" + address + "\": " + e.getMessage());
} catch (Exception e) {
System.out.println("Error initializing: " + e.getMessage());
}
}
}
Tested on Glassfish 4, hope that helps.

Related

Java Proxy Socket not connecting to client

I will post my code below, a little background.
I am trying to connect to a gameserver on port 9339. my local port changes each time. The aim is to pass the packets through the proxy and display the info in the command line.
The client connects to the remote host using bluestacks which is running the game.
Code:
import java.io.*;
import java.net.*;
public class proxy {
public static void main(String[] args) throws IOException {
try {
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(0);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.err.println(e);
}
}
/**
* runs a single-threaded proxy server on
* the specified local port. It never returns.
*/
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
System.out.println("Client Accepted!");
final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
// Make a connection to the real server.
// If we cannot connect to the server, send an error to the
// client, disconnect, and continue waiting for connections.
try {
server = new Socket(host, remoteport);
System.out.println("Client connected to server.");
} catch (IOException e) {
PrintWriter out = new PrintWriter(streamToClient);
out.print("Proxy server cannot connect to " + host + ":"
+ remoteport + ":\n" + e + "\n");
out.flush();
client.close();
System.out.println("Client disconnected");
continue;
}
// Get server streams.
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();
// a thread to read the client's requests and pass them
// to the server. A separate thread for asynchronous.
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
// Start the client-to-server request thread running
t.start();
// Read the server's responses
// and pass them back to the client.
int bytesRead;
try {
while ((bytesRead = streamFromServer.read(reply)) != -1) {
streamToClient.write(reply, 0, bytesRead);
streamToClient.flush();
}
} catch (IOException e) {
}
// The server closed its connection to us, so we close our
// connection to our client.
streamToClient.close();
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
Basically the last thing that is printed out is "Starting proxy for gamea.clashofclans.com:9339 on port (whatever it chose).
Hopefully someone can help me.
I have this problem too, I don`t have enough time to correct this but i think using thread is that is why all mistake.
check your proxy for working on browser setting( May be proxy had problem)
If not,
I suggest to don`t use thread. maybe mutual exclusion occurs.
Your code is correct.It is working fine so you don't need any fix. What is happening is , your serverSocket in your proxy class is waiting for client to connect. that's why it is not going forward. What you need to do is, create a client and connect to it.
follow the step :
run your proxy.
then run your client
for the client, you can use this code,
public static void main(String[] args) throws IOException {
try {
int remoteport = 9339;
String host="127.0.0.1";
makeConnection(host, remoteport);
System.out.println("connection successful!");
} catch (Exception e) {
System.err.println(e);
}
}
public static void makeConnection(String host, int remoteport) throws IOException {
while (true) {
Socket client = null;
try {
client = new Socket(host, remoteport);
System.out.println("Client connected to server.");
break;
} catch (IOException e) {
System.err.println(e);
} finally {
if (client != null)
client.close();
if (client != null)
client.close();
}
}
}

Is it possible to use an applet as a server with Java?

I'm just getting into networking and I'm quite confused about how I can use a server from a server hosting company for a game. At the moment, the program allows a user to host the server from their computer and it works to some degree. The only problem is that when my friends connect to the game from other states their ping is super high and they lag horribly.
I'm now using a site that gives out free web hosting space. I've believe I've jumped through most of the permission hoops that I need in order to use sockets and the applet works just like it does while running on my computer.
Below is an excerpt from the Game class. If I use InetAddress.getLocalHost().getHostAddress() to get the IP, it gets the IP from the user who is using the client and makes them the server host. This works, but it doesn't solve my problem of lag.
Game.java
public synchronized void start() {
running = true;
thread = new Thread(this, NAME + "_main");
thread.start();
if (JOptionPane.showConfirmDialog(this, "Do you want to run the server") == 0) {
socketServer = new GameServer(this);
socketServer.start();
}
this.ipAddress = "31.170.163.198";
//this.ipAddress = InetAddress.getByName(ipAddress).toString();
System.out.println("IP: " + this.ipAddress);
socketClient = new GameClient(this, this.ipAddress);//Inet4Address.getLocalHost().getHostAddress());
try {
Player.setIp(Inet4Address.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
socketClient.start();
}
I want the server that contains the jar to host the server. We all ping test each other and we mostly all get timed out, however, when we ping the server's ip we all get decent ping. When I enter the Server's IP (I find this info in the control panel) manually the server/client fail to make a connection. I've tried using both the website IP and the server IP that are provided. I've also tried using the applet.getCodeBase().getHost() in order to retrieve the IP from the server but that IP failed to send/receive data as well.
Is what I'm trying to do possible? Is the server blocking me from using it in that way? Do I need to rewrite the whole program and look into java servlets to achieve my goal?
I apologize if the question is silly. I've been working on this for the past 3-4 days with very little progress. I've searched around a bit on using a server in this manner and I've found very little on the topic.
Below are some excerpts from other relevant pieces of code.
GameClient.java
package fraccas.java2dgame.net;
public class GameClient extends Thread {
private InetAddress ipAddress;
private DatagramSocket socket;
private Game game;
public long lastPing = 0;
public static int ping = 0;
public GameClient(Game game, String ipAddress) {
this.game = game;
try {
this.socket = new DatagramSocket();
this.ipAddress = InetAddress.getByName(ipAddress);
System.out.println("IP: " + InetAddress.getByName(ipAddress));
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
if (packet != null)
{
long current = System.currentTimeMillis();
ping = (int) (current - lastPing);
lastPing = current;
}
} catch (IOException e) {
e.printStackTrace();
}
this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
}
}
private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
Packet packet = null;
switch (type) {
default:
case INVALID:
break;
case LOGIN:
packet = new Packet00Login(data);
handleLogin((Packet00Login) packet, address, port);
break;
case DISCONNECT:
packet = new Packet01Disconnect(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] "
+ ((Packet01Disconnect) packet).getUsername() + " has left the world...");
game.level.removePlayerMP(((Packet01Disconnect) packet).getUsername());
break;
case MOVE:
packet = new Packet02Move(data);
handleMove((Packet02Move) packet);
}
}
public void sendData(byte[] data) {
//if (!game.isApplet) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 3333);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
//}
}
private void handleLogin(Packet00Login packet, InetAddress address, int port) {
System.out.println("[" + address.getHostAddress() + ":" + port + "] " + packet.getUsername()
+ " has joined the game...");
PlayerMP player = new PlayerMP(game.level, packet.getX(), packet.getY(), packet.getUsername(), address, port);
game.level.addEntity(player);
}
private void handleMove(Packet02Move packet) {
this.game.level.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getNumSteps(),
packet.isMoving(), packet.getMovingDir());
}
}
GameServer.java
package fraccas.java2dgame.net;
public class GameServer extends Thread {
private DatagramSocket socket;
private Game game;
private List<PlayerMP> connectedPlayers = new ArrayList<PlayerMP>();
public GameServer(Game game) {
this.game = game;
try {
this.socket = new DatagramSocket(3333);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
}
}
private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
Packet packet = null;
switch (type) {
default:
case INVALID:
break;
case LOGIN:
packet = new Packet00Login(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] "
+ ((Packet00Login) packet).getUsername() + " has connected...");
PlayerMP player = new PlayerMP(game.level, 100, 100, ((Packet00Login) packet).getUsername(), address, port);
this.addConnection(player, (Packet00Login) packet);
break;
case DISCONNECT:
packet = new Packet01Disconnect(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] "
+ ((Packet01Disconnect) packet).getUsername() + " has left...");
this.removeConnection((Packet01Disconnect) packet);
break;
case MOVE:
packet = new Packet02Move(data);
this.handleMove(((Packet02Move) packet));
}
}
public void addConnection(PlayerMP player, Packet00Login packet) {
boolean alreadyConnected = false;
for (PlayerMP p : this.connectedPlayers) {
if (player.getUsername().equalsIgnoreCase(p.getUsername())) {
if (p.ipAddress == null) {
p.ipAddress = player.ipAddress;
}
if (p.port == -1) {
p.port = player.port;
}
alreadyConnected = true;
} else {
// relay to the current connected player that there is a new
// player
sendData(packet.getData(), p.ipAddress, p.port);
// relay to the new player that the currently connect player
// exists
//packet = new Packet00Login(p.getUsername(), p.x, p.y);
Packet00Login packetNew = new Packet00Login(p.getUsername(), p.x, p.y);
sendData(packetNew.getData(), player.ipAddress, player.port);
}
}
if (!alreadyConnected) {
this.connectedPlayers.add(player);
}
}
public void removeConnection(Packet01Disconnect packet) {
this.connectedPlayers.remove(getPlayerMPIndex(packet.getUsername()));
packet.writeData(this);
}
public PlayerMP getPlayerMP(String username) {
for (PlayerMP player : this.connectedPlayers) {
if (player.getUsername().equals(username)) {
return player;
}
}
return null;
}
public int getPlayerMPIndex(String username) {
int index = 0;
for (PlayerMP player : this.connectedPlayers) {
if (player.getUsername().equals(username)) {
break;
}
index++;
}
return index;
}
public void sendData(byte[] data, InetAddress ipAddress, int port) {
//if (!game.isApplet) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
try {
this.socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
//}
}
public void sendDataToAllClients(byte[] data) {
for (PlayerMP p : connectedPlayers) {
sendData(data, p.ipAddress, p.port);
}
}
private void handleMove(Packet02Move packet) {
if (getPlayerMP(packet.getUsername()) != null) {
int index = getPlayerMPIndex(packet.getUsername());
PlayerMP player = this.connectedPlayers.get(index);
player.x = packet.getX();
player.y = packet.getY();
player.setMoving(packet.isMoving());
player.setMovingDir(packet.getMovingDir());
player.setNumSteps(packet.getNumSteps());
packet.writeData(this);
}
}
The applet does not have any errors in the console at the moment. It simply does not send/receive the data.
http://critterisland.bugs3.com/public_html/index.html (Applet Link)
http://gyazo.com/a91401545b1a741f2b9fc86471bd5762 (Image of Applet)
Thanks for you time,
Fraccas
The problem is that you're using a web host which is only able to provide the files to users as opposed to actually being able to run the software you've created.
To run your software independently in the way you're wanting, your easiest option is to rent a virtual private server (VPS) which is located appropriately for your users. However, you'll need to be able to do some basic configuration on the VPS (such as install Java), and then run your server as a console application.
Not much code needs to be changed to get it working. You could use the same jar file for both the server and the client by adding a command line argument which only starts the server (i.e. "-server"). From the server computer/VPS you would then start the server by running "java -jar CritterIslandTest.jar -server" which then only starts the server and handles communication. If the command line argument is not found you can then continue with the GUI logic.

IOException after thousands of socket creation calls

Why IOException after thousands of socket creation calls?
I did a simple Server code (Java) which accepts connections then creates a thread reads the socket and sends back another character to the Client
The Client code starts to do a cycling (long enough to reproduce the issue) and in each cycle creates 50 threads in each thread creating a client socket to server machine and sends a character then reads from socket the character that the Server sends back.
Then both the Client and the Server closes the socket.
After a while I notice that on Client side I get exception in client socket creation.
Are there some limitations which I should take in consideration to work this properly or this should work in an infinite loop?
I'm thinking here to situations that maybe after a long enough cycling time the client side tries to bind the new socket to a port on client machine which is still binded to a socket which is in CLOSED state but that time period which needs to be elapsed to be freed by kernel not passed yet. (sorry don't know official name of this time period)
The client and server machines are two Linux systems in VMware.
Sounds like maybe your connection was dropped.
You forgot rule #1 in the Fallacies of Distributed Computing: The network is always reliable.
Have you set the setReuseAddress parameter to true on your ServerSocket? If not, you have to wait a quite long time before the kernel release network resources.
Thank you !
Actually this is my Server side code
public class TestServer {
public void createThread() {
System.out.println("createThread");
ServerThread servThread = new ServerThread();
servThread.start();
}
public static final void main(String[] args) {
ServerSocket server = null;
try {
System.out.println("Started");
server = new ServerSocket(12345);
}
catch(IOException ex) {
System.out.println("Server: Exception at socket creation: " + ex.getMessage());
}
try {
while(true) {
Socket clientSock = server.accept();
System.out.println("Connection Accepted: server: "+clientSock.getLocalPort()+", Client: "+clientSock.getPort());
ServerThread servThread = new ServerThread(clientSock);
servThread.start();
}
}
catch(IOException ex) {
System.out.println("Server: Exception at socket accept: " + ex.getMessage());
}
}
}
class ServerThread extends Thread {
private Socket sock;
public ServerThread() {}
public ServerThread(Socket sock) {
this.sock = sock;
}
public void run() {
InputStream is = null;
OutputStream os = null;
try {
is = sock.getInputStream();
os = sock.getOutputStream();
}
catch(IOException ex) {}
try {
int b = is.read();
System.out.println("server: received = " + (char)b);
}
catch(IOException ex) {
System.out.println("Server: IOException at read = " + ex.getMessage());
}
try {
os.write('R');
os.flush();
}
catch(IOException ex) {
System.out.println("Server: IOException at write = " + ex.getMessage());
}
try {
sock.close();
}
catch(IOException ex) {
System.out.println("Server: IOException at close = " + ex.getMessage());
}
}
}
and this is the Client part:
public class TestClient {
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("Usage: java TestClient <ServerIP> <nbThreads> <cycle> <delay>");
System.exit(1);
}
String host = args[0];
int nbThreads = Integer.parseInt(args[1]);
int cycle = Integer.parseInt(args[2]);
int delay = Integer.parseInt(args[3]);
for (int i = 0; i<cycle; i++) {
for (int j = 0; j<nbThreads; j++) {
ClientThread clThread = new ClientThread(host);
clThread.start();
}
/* try {
Thread.sleep(delay);
}
catch (Exception ex) {} */
}
}
}
class ClientThread extends Thread {
private String host;
public ClientThread(String host) {
this.host = host;
}
public void run(){
for (int i=0; i<3; i++) {
Socket clientSock = null;
try {
clientSock = new Socket(host, 12345);
}
catch(IOException ex) {
System.out.println("Client: IOException at socket creation = " + ex.getMessage());
}
OutputStream os = null;
InputStream is = null;
try {
os = clientSock.getOutputStream();
is = clientSock.getInputStream();
}
catch (IOException ex) { }
try {
os.write('B');
os.flush();
}
catch (IOException ex) {
System.out.println("Client: IOException at write = " + ex.getMessage());
}
try {
int reply = is.read();
System.out.println("Client: reply = " + (char)reply);
}
catch(IOException ex) {
System.out.println("Client: IOException at read = " + ex.getMessage());
}
try {
clientSock.close();
}
catch(IOException ex) {
System.out.println("Client: IOException at close = " + ex.getMessage());
}
}
}
}
I'm testing with 60 threads and 1000 cycle and no delay.
I was wrong in my first question, the exception comes from the is.read() call after a while and it is 'Connection reset' exception.
I did this sample code to simulate the problem I'm getting in my application code where I'm getting the exception during the client socket creation ... but it seems I need to find further what is the difference netween this and my application code.
However I think would help me also to understand why after a while I'm getting the 'Connection reset' exception on the client side after a while.
Is that possible that on the server side once os.write('R') happened the sock.close() happens so fast that on the client side the is.read() call hasn't reached yet. Sound strange :)
Also not sure on which socket I should use the setReuseAddress function. Isn't on the client side, because there I'm creating again and again the sockets... although now I'm not getting the exception at client socket creation.
Thanks !

Server-Client communication problem

i'm working with an example of client-server programm on Java. I faced such a problem:
I start the server with 8080 port and a localhost, than I start a client and make a request. As soon as the request done both programms close theri sockets, so i can't repeat my actions. How can i use the same client and the same server to make more than one request?
public class Network extends Thread
{
MasterEdit ME = new MasterEdit();
private Socket _socket;
InputStream is; //Data streams
OutputStream os;
/**
* Network class constructor
*/
public Network(int port, int backlog, InetAddress address)
{
//We create an object of SocketFactory
SocketFactory sf = new SocketFactory();
//Save server socket
ServerSocket ss = null;
try
{
if(address == null) //If there is no host
{
if(backlog <= 0) //If backlog is not given we create it with port
{ ss = sf.createServerSocket(port);
System.out.println("Success");
}
else
ss = sf.createServerSocket(port, backlog); //If backlog is given we just create it
}
else
ss = sf.createServerSocket(port, backlog, address); //If everything is given we create it using data
}
catch(Exception e)
{
//Exception with creation of socket
System.err.println("Failed open server socket");
System.exit(1); //Stop program and send 1 as a exception-code
}
while(true) //Listening to the socket
{
try
{
StartThread(ss.accept()); //If client has connected we send him to the daemon
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Start daemon-tool when client has connected
*/
private void StartThread(Socket ss)
{
_socket = ss; //initializing of global variable
setDaemon(true); //anounce that new potok is daemon
setPriority(NORM_PRIORITY); //set the priority
start(); //Start it
}
#Override
public void run()
{
byte buffer[] = new byte[64*1024]; //buffer in 64 kb
try
{
is = _socket.getInputStream();
os = _socket.getOutputStream(); //Initializing the output stream to a client
String toClient = SearchRequest(new String(buffer, 0, is.read(buffer)));
os.write(toClient.getBytes()); //Sending an answer
}
catch(Exception e)
{
e.printStackTrace();
}
}
private String SearchRequest(String request)
{
String info = ""; //Initializing of a variable
if(request.equalsIgnoreCase("info")) //Check the request
{
//Adding data
info += "Virtual Machine Information (JVM)n";
info += "JVM Name: " + System.getProperty("java.vm.name")+"n";
info += "JVM installation directory: " + System.getProperty("java.home")+"n";
info += "JVM version: " + System.getProperty("java.vm.version")+"n";
info += "JVM Vendor: " + System.getProperty("java.vm.vendor")+"n";
info += "JVM Info: " + System.getProperty("java.vm.info")+"n";
return info; //Give the answer
}
if(request.charAt(0)=='0') {
StringTokenizer rm = new StringTokenizer(request, " \t\n\r,:");
rm.nextToken();
ME.MasterDell(Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()));
return "Successfully deleted";
}
if(request.charAt(0)=='1'){
StringTokenizer temp = new StringTokenizer(request, " \t\n\r,:");
temp.nextToken();
ME.MasterAdd(Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), temp.nextToken());
return "Successfully added";
}
this.ClostIt();
return "Bad request"; //bad request
}
public void ClostIt() {
try {
is.close();
os.close();
_socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It's server part. It usess SocketFactory class but mainly it just creates a socket in the begining. In main programm i call new Network(PORT, BACKLOG, InetAddress.getByName(host));
I am guessing in your server program you don't have a loop but rather something like this:
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = server.accept();
//process the client connection ...
//done, exit!
}
rather than
public static void main( String args[] ) {
ServerSocket server = new ServerSocket(...);
Socket con = null;
while( condition /* e.g. shutdown server message received */ ) {
con = server.accept();
//process the client connection ...
//then keep waiting for the next request
}
//done, exit!
}
Bear in mind the above sample only processes one client at a time! you will need to step into multi-threading for processing simultaneous clients.
This is a good starter for a multi threaded server
http://www.kieser.net/linux/java_server.html
Mark

tcp session in java

i want to connect morethan one client at a time to the server and also communicate server to all the clients.
how server recognize each client. and how to send data to a particular client?
consider , there are 3 clients A,B,C. all the clients are connected to the server. the server wants to send message to B. how its done ?
If i understand you right - all you need is not bind socket for one connection.
Your client code will looks like that:
Client class:
public class TCPClient {
public TCPClient(String host, int port) {
try {
clientSocket = new Socket(host, port);
} catch (IOException e) {
System.out.println(" Could not connect on port: " + port + " to " + host);
}
}
Server(host) class:
public class TCPListener {
public TCPListener(int portNumber) {
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println("Could not listen on port: " + portNumber);
}
System.out.println("TCPListener created!");
System.out.println("Connection accepted");
try {
while (true) {
Socket clientConnection = serverSocket.accept();
//every time client's class constructor called - line above will be executed and new connection saved into Socket class.
}
} catch (Exception e) {
e.printStackTrace();
}
}
That is simplest example. More can be found here:
http://www.oracle.com/technetwork/java/socket-140484.html

Categories