Help on Server Socket Programming??????
hello Friends,
I need your help on following:
I am the only person working on this project and the company wants me to prepare a infrastructure of this project and I should also give a demo of this project to my seniors. I will breif you up with my project:
1. There is this gif image of distillation column. i will be publishing it using JApplet or Applet.
2. This Image must be seen on internet.
3. On the circle of these Image the user will click(In all there are five circles, called as controllers)and a dialog box should open thru which user will input the float values(I am using the JOptionPane class to open this dialog box).
4. The inputed values will the be given to the C program which is the simulator for distillation column.
5. The C program will generate the output through iterations(Code entirely in C), the output of each program will then be poped up to over the image beside the respective controlled or under the respective controller but definetely over the same gif file.
6. The number of iteration will depend on how fast the C program converges the inputer parameters. And each output must be show over the gif image and when the final iteration value will appear it should remain on the image until some new value is inputted by the user again by clicking on any of the circle.
The proposed theory to do this project accoding to me is as follows:
1. Since each value must be thrown to the user. I beleive this is a real time project. So I decided to use Client Server Networking technology provided by java.
2. Then I figured out that in this project there should be 2 clients One is the GUI which is the Image screen to receive the input from the user and to show the output to the user. Second client is a java program sitting behind the server which will receive this input data from user and it will have an NATIVE method through which all this input will be given to the C simulator program.
3. The middle bridge between these two clients will be a server. Which will just pass the data to and fro from both the clients.
3. The C program will perform iterations using these input values from second client. This C program will then give each iterations output to the Java program using JNI technology. This second client then sends this output value to the GUI clients through server.
Well another very important thing, I am inexperience in the field of software so I had to do a lot of R&D and this is what I found out. Frankly I am really not sure whether this is the right path to approach to this project or there is some other correct and realistic way than this? Well friends i would certainly request you if you can suggest some other simple or rather correct path or else if this is the right path then would you please suggest me the possible hiches or perticular points where I should concentrate more.
Well i am eagerly waiting for your reply.
Since you are publishing your results on the net , it will be a better idea to use JSP?Servlet/Beans architecture instead of swing
I will propose a architecture as follows:
Client : Standard Browsers, IE and NS
Middle Tier: Java Webserver/Application Server
This will depend on your budget. If u have a fat allowance go for weblogic/websphere . If u are operationg on shoe string budget try for apache , etc
In the server tier code your application in the follwing architecture
JSP for presentation: Distillation towers picture, input boxes .. etc
Servlets for business logic invocation and routing requests: Your JSP submits input values to servlets, which does the processing using Java Bean Components. Since you have a lot of Logic written in C I would suggest to encapsulate these in JavaBean components using JNI technology and reuse the code.
After processing the servlet again forwards the response to another JSP for output
Advantages:
1.Your clients can be thin as most of the processing is done at the server
2. Thread Management is taken care of by your webserver, which otherwise would be a headache
3. Writing this through low level socket programming will be much more difficult as you will write your own protocol for communication this will be error prone and not scalable
If you still decide to go for traditional client server programming using swing, use RMI for communication as I insist that socket programming is very very cumbersome...using your own protocols
hope this helps
Shubhrajit
Similar Messages
-
Can i run UDP client and UDP server socket program in the same pc ?
hi all.
when i execute my UDP client socket program and UDP server socket program in the same pc ,
It's will shown the error msg :
"Address already in use: Cannot bind"
but if i run UDP client socket program in the remote pc and UDP server socket program run in local pc , it's will success.
anybody know what's going on ?
any help will be appreciated !bobby92 wrote:
i have use a specified port for UDP server side , and for client define the server port "DatagramSocket clientSocket= new DatagramSocket(Server_PORT);"Why? The port you provide here is not the target port. It's the local port you listen on. That's only necessary when you want other hosts to connect to you (i.e. when you're acting as a server).
The server should be using that constructor, the client should not be specifying a port.
so when i start the udp server code to listen in local pc , then when i start UDP client code in local pc ,i will get the error "Address already in use: Cannot bind"Because your client tries to bind to the same port that the server already bound to. -
Help required in socket programming...
hi all,
I have a server socket which is suppose to accept multiple clients and communicate with them... In case I m successfull able to connect only one client and communicate with the server where as the 2nd client is connected but i am not able to establish the communication.. can u please help me in this matter
Thank U
ParimalaLook at this Sample.
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Mserv extends JFrame
public Mserv()
super("J21server v1.4.1");
setBounds(10,10,400,420);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent ev)
{ dispose();
System.exit(0);}});
setVisible(true);
public void go(Socket clnt)
Server server = new Server(clnt);
server.start();
public class Server extends Thread
Socket clnt = null;
public Server(Socket soc)
clnt = soc;
public void run()
OutputStream out = null;
InputStream in = null;
int i = 0;
byte b[] = new byte[1024];
try
out = clnt.getOutputStream();
in = clnt.getInputStream();
while ((i = in.read(b)) > 0)
catch (IOException e){}
try
in.close();
out.close();
catch (IOException e){}
public static void main (String[] args)
ServerSocket servS = null;
Socket clnt = null;
Mserv mserv = new Mserv();
try
servS = new ServerSocket(4444);
while (true)
clnt = servS.accept();
mserv.go(clnt);
catch (IOException e)
e.printStackTrace();
Noah -
Server socket programming and thread
hello,
briefly this is what i have sought out to do : the server waits for the client indefinitely,upon a client requesting for service by writing a service id into the socket, a new thread of the type id as read by the server which is a sub-class of the Server (main-class) is exec'd.
the problem as i understand is that the client can send as much of data as it desires to the server and the thread can read the data it receives by the clients.the server(thread) fails to write reply to the client;eventhough out.write() is successful;the client is blocked in read() indefinitely.is it because of the thread which runs at a different port the client does not know and the server is not redirecting response to the client.
how do i read what the server(thread) writes onto the socket from the clients.thanks again,just check out this code please
public class Server extends Thread //create a multi-threaded server
/* *Creates a new instance of Server */
String serverAddr=CodeServer.ServerRun.SERVER_IP_ADDR;
int serverPortNum=CodeServer.ServerRun.SERVER_TCP_PORT;
ServerSocket sSock;
Socket cSocket;
int requestID=0;
boolean debug=true;
InputStream in =null;
OutputStream out=null;
Server ()
Server (Socket csocket)
this.cSocket = csocket;
/* start the server at specifed portNum */
private void initialise ()
try
//start the server at serverPortNum
sSock=new ServerSocket (serverPortNum);
catch (IOException ex)
ex.printStackTrace ();
/* console output of status of server */
if(debug==true)
System.out.println ("Server waiting @ "+sSock);
private void acceptRequest ()
try
this.cSocket=sSock.accept ();
if(debug==true)
System.out.println ("client socket @ "+cSocket);
catch (IOException ex)
ex.printStackTrace ();
private void readRequestID ()
/*step 1: determine the type of server before threading
*a request the the type of server got by the request ID
* number */
try
in =cSocket.getInputStream ();
requestID =in.read ();
out =cSocket.getOutputStream ();
if(debug==true)
System.out.println ("accross the client:"+requestID);
catch (IOException ex)
ex.printStackTrace ();
private void execThreadForRequest ()
/*step 2: after requestID is received on the socket.
*its time to decide the server to thread the control into.
switch(requestID)
case 1: //invoke the RegisterServer thread
new CodeServer.Core.RegistrationServer (this.cSocket).start ();
break;
case 2: //invoke the ListingServer thread
break;
case 3: //invoke the MessageTransferServer thread
break;
case 4: //invoke the CallSetupServer thread
break;
case 5: //invoke the DisconnectServer thread
break;
case 6: //invoke the ChangeUserStatusServer thread
break;
public void run ()
// client processing code here==super class does nothing here
public static void main (String args[]) throws Exception
Server s=new Server ();
s.initialise ();
/* start indefinitely the main server thread */
while (true)
/* accept() blocks the server for a request
a new request is put into a thread for processing */
s.acceptRequest (); //initialise the clientSocket
s.readRequestID (); //get the actual requested service
s.execThreadForRequest (); //start the actual server thread
/**registration service class;
*registers the IP address of the caller,callee and the status
*adds the caller to the hash table and updates status
class RegistrationServer extends Server
Socket cSocket;
InetAddress clientAddr;
DataInputStream inStream;
DataOutputStream outStream;
//Socket s=new Socket()
RegistrationServer (Socket cSocket)
this.cSocket=cSocket;
clientAddr =cSocket.getInetAddress ();
try
//init for reading status and custom message.
inStream =new DataInputStream (cSocket.getInputStream ());
outStream =new DataOutputStream (cSocket.getOutputStream ());
catch (IOException ex)
ex.printStackTrace ();
if(CodeServer.ROO.DEBUG==true)
System.out.println ("register server:"+cSocket
+" host ip:"+clientAddr.getHostName ());
public void run ()
int status=0;
String custMesg=null;
try
/* read the custom message */
if(inStream.available ()>0)
try
custMesg=inStream.readUTF ();
System.out.println (""+custMesg);
catch(EOFException e)
e.printStackTrace ();
else
custMesg="";
catch (IOException ex)
ex.printStackTrace ();
try
here is the problem, i found if i try reading accross the client
i only receive a junk value 81 always */
outStream.write(1); //write success
outStream.flush();
catch (IOException ex)
ex.printStackTrace ();
}and with the client GUI :thanks for the help.please do find time to help me out with a suggestion or two on this code. -
Server socket programming issue
Hi there and thanks for visiting my post,
I'm writing a instant message application. I've written a multi-threaded server that constant listens for socket connections on port 4001. When a connection is received by the server, it adds the thread (client) connection to an array (of fixed size, I allow a max of 100 connections or so) and starts the thread. Here's the code:
import java.io.*;
import java.util.*;
import java.net.*;
* @author Stephen
public class Main {
static ServerSocket sock = null;
static pmClientHandler conn;
static Socket client = null;
static int port = 4001;
static int MAX_CONNECTIONS = 100;
static pmClientHandler t[] = new pmClientHandler[MAX_CONNECTIONS]; // array that holds threads holds a max of 100 now
/** Creates a new instance of Main */
public Main() { }
* Instantiate server listener
* @param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
try {
sock = new ServerSocket(port); // listen on port
} catch (IOException e) {
System.out.println("Cannot create server on port "+port+".");
System.exit(1);
System.out.println("Pita messenger server ready on port "+port+". Listening for connections...\n\n");
while (true) { // infinite loop to listingen for many connections
try {
client = sock.accept(); // accept connection
for (int i =0; i < MAX_CONNECTIONS; i++) {
if (t[i] == null) {
(t[i] = new pmClientHandler(client,t,MAX_CONNECTIONS)).start();
break;
} catch (IOException e) { // ERROR ACCEPTING CONNECTION
} // end infini. loop listening for remote socket connections
}Again, each instance thread object of pmClientHandler constantly listens for incoming messages from the client application. Here's the code for that class.
import java.util.*;
import java.net.*;
import java.io.*;
public class pmClientHandler extends Thread {
public String username = "";
private boolean userValidated = false;
public boolean userAway = false;
public boolean userInvisible = false;
public boolean userBusy = false;
private ArrayList currentBuddyList;
public Socket connection;
public pmClientHandler t[];
private Scanner reciever;
public PrintStream sender = null;
private int MAX_CONNECTIONS;
private boolean isConnected = false;
/** Creates a new instance of pmClientHandler */
public pmClientHandler(Socket s, pmClientHandler[] newThread, int maxc) {
connection = s; // hand over socket
MAX_CONNECTIONS = maxc;
t = newThread; // hand over thread. We now have new populate array of clients in t[]
isConnected = true; // user connected
try { // create IO streams for this particular client
reciever = new Scanner(connection.getInputStream());
sender = new PrintStream(connection.getOutputStream(), true); //auto flush true
} catch (IOException e) { close(); }
* Required method by threads. Method is called when thread is executed.
public void run() {
String clientMessage;
pmServerMessenger resource = new pmServerMessenger();
while(isConnected) {
// Determine username and password request
clientMessage = reciever.nextLine().trim();
/////////////////////// HANDLE PROTOCOL / MESSAGES /////////////////////////////////
// So we know user has established a connection to the server but has not yet logged in yet.
if (clientMessage.toUpperCase().startsWith("ECHO")) { sender.println("ECHO BACK, HELLO CLIENT"); }
if (clientMessage.startsWith("LOGIN")) { // client wishes to log in
clientMessage = clientMessage.substring(5).trim();
if (clientMessage.indexOf(" ") != -1) {
String suppliedUsername, suppliedPassword;
suppliedUsername = clientMessage.substring(0, clientMessage.indexOf(" ")).trim();
suppliedPassword = clientMessage.substring(clientMessage.indexOf(" ")).trim();
// Valid user
if (resource.validateUser(suppliedUsername, suppliedPassword)) {
sender.println("ACDFG324323DSSDGTRR54745345DFGDFSE3423423DHDFHER4565DFGDFGERT"); // send key to client
userValidated = true; // set flag to allow user to access server resources.
this.username = suppliedUsername;
} else {
sender.println("INVALIDLOGIN");
} else {
sender.println("INVALIDLOGIN");
this.close();
} // end user login routine //////////////////////////////////////////////
if (clientMessage.toUpperCase().startsWith("LOADBUDDYLIST")) {
if (isConnected && userValidated) {
ArrayList thisUsersBuddyList = resource.getBuddyList(this.username);
for (int i = 0; i < thisUsersBuddyList.size(); i++) {
String currBuddy = (String) thisUsersBuddyList.get(i);
if (currBuddy != "" && currBuddy != null) {
sender.println(currBuddy);
sender.println("ENDBUDDYLIST"); // let client know we're done sending client buddy list
if (clientMessage.toUpperCase().startsWith("ISONLINE")) {
String usrToCheck = clientMessage.substring(8).trim();
if (isOnline(usrToCheck)) {
sender.println("YES "+usrToCheck);
} else {
sender.println("NO "+usrToCheck);
if (clientMessage.toUpperCase().startsWith("ISAWAY")) {
String usrToCheck = clientMessage.substring(6).trim();
if (isUserAway(usrToCheck)) {
sender.println("Z "+usrToCheck); // is away
} else {
sender.println("X "+usrToCheck); // not away
if (clientMessage.toUpperCase().startsWith("CLIENTAWAY")) {
String usrToCheck = clientMessage.substring(10).trim();
if (!usrToCheck.trim().equals("")) {
setClientAsAway(usrToCheck);
if (clientMessage.toUpperCase().startsWith("CLIENTBACK")) {
String usrToCheck = clientMessage.substring(10).trim();
if (!usrToCheck.trim().equals("")) {
setClientAsBack(usrToCheck);
// Exit the clients connection to the server.
if (clientMessage.toUpperCase().startsWith("EXIT")) {
sender.println("GOODBYE");
this.close();
if (clientMessage.toUpperCase().startsWith("WHOISONLINE")) {
whoisOnline();
if (clientMessage.toUpperCase().startsWith("DISPATCHIM")) {
String imStr = clientMessage.substring(1).trim();
String to = imStr.substring(0,imStr.indexOf(" ")).trim();
String imMsg = imStr.substring(imStr.indexOf(" ")).trim();
dispatchIM(to,imMsg);
} // end while is connected
} // End run method
public synchronized void addIMToQueue(String from, String msg) {
instantMessage im = new instantMessage(from,msg);
imQueue.addLast(im);
private synchronized void getInstantMessages() {
while (!imQueue.isEmpty()) {
instantMessage tmpMsg = imQueue.remove();
String tmpHandle = tmpMsg.getHandle();
String tmpImMsg = tmpMsg.getMsg();
sender.println("L "+tmpHandle+" "+tmpImMsg);
sender.println("IMPOPDONE");
private void dispatchIM(String to, String m) {
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t.username.trim().equals(to)) {
pmClientHandler x = t[i];
PrintStream ps = x.sender;
ps.println("IMMSG "+this.username+" "+m);
* Method will relay back to client a list of who's online. When it's finished
* the command DONELISTING is dispatched.
private void whoisOnline() {
for(int i=0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null && t[i].username.trim() != "")
sender.println(t[i].username);
sender.println("DONELISTING"); // so client knows we're done
} // END whoisOnline METHOD
private boolean isOnline(String user) {
boolean isOn = false;
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null && t[i].username.trim().equals(user.trim())) {
isOn = true; break;
return isOn;
private boolean isUserAway(String user) {
boolean tmpIsAway = false;
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t[i].username.trim().equals(user)) {
if (t[i].userAway) {
tmpIsAway = true;
break;
} else {
break;
return tmpIsAway;
private void setClientAsAway(String user) {
//this.userAway = true;
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t[i].username.trim().equals(user)) {
t[i].userAway = true;
private void setClientAsBack(String user) {
//this.userAway = false;
//this.userBusy = false;
//this.userInvisible = false;
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t[i].username.trim().equals(user)) {
t[i].userAway = false;
t[i].userBusy = false;
t[i].userInvisible = false;
private boolean isUserBusy(String user) {
boolean tmpIsBusy = false;
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t[i].username.trim().equals(user)) {
if (t[i].userBusy) {
tmpIsBusy = true;
break;
} else {
break;
return tmpIsBusy;
private boolean isUserInvisible(String user) {
boolean tmpIsInvisible = false;
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t[i].username.trim().equals(user)) {
if (t[i].userInvisible) {
tmpIsInvisible = true;
break;
} else {
break;
return tmpIsInvisible;
* Method will close the connection to the server.
* It will also free up array location for any new connections
private void close() {
if (isConnected) {
try {
connection.close();
isConnected = false;
userValidated = false;
System.out.println("User " + username + " has disconnected from the Pita Messenger server.");
for(int i=0; i < MAX_CONNECTIONS; i++)
if (t[i]==this) t[i]=null; // set array element to null so we can accept another
// connection had we been maxed out
} catch (IOException e) { }
} // end pmClientHandler class
Now finally for my problem...this all works EXACTLY as expected when I telnet to the server. My client GUI application has an issue though. When I want to send an IM to a particular user...the thread code above that listens for *DISPATCHIM* get's who the IM is to and what the message is in the following protocol format *DISPATCHIM to msg* and call the following private method:private void dispatchIM(String to, String m) {
for (int i = 0; i < MAX_CONNECTIONS; i++) {
if (t[i] != null) {
if (t[i].username.trim().equals(to)) {
pmClientHandler x = t[i];
PrintStream ps = x.sender;
ps.println("IMMSG "+this.username+" "+m);
Basically, if not obvious, what I'm doing here is iterating through the array of client connection threads and finding the client thread that belongs who this message is to, and accessing the sender object and dispatching to the IM to that client. Again, all works perfectly in telnet. However, my client GUI is not recieving any data. With all my testing, it seems that I am only able to access and modify strings and boolean variables, however it's like I've lost the sender object (only in my GUI app). This is really bugging the hell out of me and I've spent days trying to figure this out. Something is just not right. My client app has a dispatcher thread that constantly listens for incoming connects (if a buddy is online, or an instant message). This is the run method of that class:public void run() {
String data;
while(true) {
try {
try {
data = reciever.nextLine();
if (!data.trim().toUpperCase().startsWith("YES") && !data.trim().toUpperCase().startsWith("NO") && !data.trim().toUpperCase().startsWith("X") && !data.trim().toUpperCase().startsWith("Z")) {
System.out.println("Foreign command: "+data);
} catch (Exception e) { System.out.println("ERR: "+e); break; }
// pass any data returned at any time during to the serverListener method
serverListener(data);
} catch (Exception e) { }
* Method is used to handle all incoming messages from the server.
private void serverListener(String data) {
if (data.trim().toUpperCase().startsWith("IMMSG")) { // Handle incoming im
String imStr = data.substring(1).trim();
String imFrom = imStr.substring(0,imStr.indexOf(" ")).trim();
String imMsg = imStr.substring(imStr.indexOf(" ")).trim();
// Check to see if we have any IM sessions open already
if (isChatWithBuddyOpen(imFrom)) {
imWindow thisIMSession = getIMSession(imFrom);
thisIMSession.appendBuddyMessage(imMsg);
thisIMSession.setVisible(true);
} else {
newIMSession(imFrom);
imWindow thisIMSession = getIMSession(imFrom);
thisIMSession.appendBuddyMessage(imMsg);
thisIMSession.setVisible(true);
// Garbage collection for old IM sessions
if (!imSessions.isEmpty()) {
for (int i = 0; i < imSessions.size(); i++) {
imWindow isGarbageIM = imSessions.get(i);
if (isGarbageIM == null || isGarbageIM.chatBuddy.trim().equals("")) {
imSessions.remove(i);
} else if (data.trim().toUpperCase().startsWith("Z")) { // Handle user is away response
String userResponse = data.substring(1).trim();
clientGUI.handleUserAwayMsg(userResponse, true);
} else if (data.trim().toUpperCase().startsWith("X")) { // Handle user is online response
String userResponse = data.substring(1).trim();
clientGUI.handleUserAwayMsg(userResponse, false);
} else if (data.trim().toUpperCase().startsWith("ISBUSY")) { // Handle user is busy response
} else if (data.trim().toUpperCase().startsWith("NOTBUSY")) { // Handle user is not busy
} else if (data.trim().toUpperCase().startsWith("ISINVISIBLE")) { // Handle user is invisible
} else if (data.trim().toUpperCase().startsWith("NOTINVISIBLE")) { // Handle user is not invisible
} else if (data.trim().toUpperCase().startsWith("YES")) { // Handle user is online
String userResponse = data.substring(3).trim();
clientGUI.handleUserOnlineMsg(true,userResponse);
} else if (data.trim().toUpperCase().startsWith("NO")) { // Handle user is offline
String userResponse = data.substring(3).trim();
clientGUI.handleUserOnlineMsg(false,userResponse);
} // end serverListener method
It's like my receiver object gets NOTHING. Again, this only occurs with my GUI app, in telnet. Can anyone PLEASE advise as to what might be occuring. Thanks very much. If you might really be able to help I could post the entire app and server zipped up so that you can poke through. If you help me figure this out and I understand why it's not working, I'll buy you a case of your favorite beer ;) Thanks!A couple of things.
In future Networking related questions should be posted into the Networking forum.
There is too much code here and too much page width. It's a bit overwhelming. You'll need to narrow this down a bit. From looking so far I see some potential
portocol related issues. Like the readLine. Are you sure you are always writing line breaks on the other side? And then there's the substring bits which are
going to be brittle.
My suiggestion would be to trace things through and be able to point out exactly where the code is getting stuck/failing. Even getting it narrowed down to a method
would be very helpful. -
Hello
I have my MultiThreaded java server running.
It works fine if it gets continuously client request But
client request comes after some period of time,
my server does not respond back.
My server is running through DOS window, so if I click
enter there, then it gives response.I dont know what is the problem.
Here is my server code.
package com.venable.superpages;
import java.io.*;
import java.net.*;
import java.lang.*;
public class MapServer {
public static long totalSystemTime = 0;
public static void main(String args[]) {
boolean DEBUG = true;;
int port = 5003;
int count = 0;
ServerSocket welcomeSocket = null;
try {
welcomeSocket = new ServerSocket(port);
if (DEBUG)
System.out.println("MapServer : main :" +
"Main thread about to start ");
} catch (IOException e) {
System.err.println("MapServer: main : Could not open socket");
while (true) {
try {
Socket socket = welcomeSocket.accept();
socket.setKeepAlive(true);
socket.setSoTimeout(480000);
long startTime = System.currentTimeMillis();
System.out.println("Mapserver thread start time " +startTime);
MapServerThread serverThread = new MapServerThread(socket,startTime);
if (DEBUG)
System.err.println("Mapserver : main : thread about to start ");
count++;
if (DEBUG)
System.err.println("MapServer : main :count " + count);
serverThread.start();
} catch (IOException e) {
System.err.println("IO Error");
this the thread :-
public MapServerThread(Socket socket, long time) {
this.clientSocket = socket;
requestStartTime = time;
public void run() {
System.out.println( "connecting to server");
try {
inStream = new DataInputStream(clientSocket.getInputStream());
outStream = new DataOutputStream (clientSocket.getOutputStream());
byte[] len = new byte[6];
while(true){
inStream.readFully(len);
length = Integer.parseInt(new String(len));
if(length == 0){
System.out.println(" breaking the while loop becuase of socket time out");
break;
length = length +0; // to remove leading zeroes.
System.out.println( "length="+length);
byte[] data = new byte[length];
inStream.readFully(data);
inputParam = new String(data);
if(length == 3){ // means left or right on the map special
System.out.println( "LENGTH IS 3");
getMapStatus(inputParam);
if(type.equals("01") ){
getMap();
} else{
getDirectionMap();
}else{
parseInputParameter(inputParam);
getLocationPoints(toFrom);
}catch(EOFException ex){
System.out.println( "Here EOF Exception");
try{
outStream.close();
inStream.close();
clientSocket.close();
}catch( Exception e){
}catch(Exception e){
System.out.println( "Here general Exception");
try{
outStream.writeBytes(servererror);
outStream.close();
inStream.close();
clientSocket.close();
}catch(Exception ex){
}What you need to do is just call read(). This will block and only return when there's some data on the socket. At that point, call socket.(getInputStream()).available() to find out how much data there is, and create new byte[] (or char[]) and read the available bytes
-
SOCKET PROGRAMMING HELP NEEDED!!!!
hi,
I got an idea of establishing socket connection with all clients from SERVER through the windows command
called (arp -a). when we type the stated command on dosprompt in server, it gives the list of current system's
ipaddress.....switched on. SO i can establish socket connections in a for loop where i can take the following ipaddress from output listed from command.
i've written the code to call the command in JAVA.
i write the dosprompt output in a file named list1.txt
import java.util.*;
import java.io.*;
import java.io.File;
public class RunCommand
public static String[] runCommand(String cmd) throws IOException
ArrayList list = new ArrayList();
Process proc = Runtime.getRuntime().exec(cmd);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null)
list.add(str);
try
proc.waitFor();
}catch (InterruptedException e)
System.err.println("process was interrupted");
// check its exit value
if (proc.exitValue() != 0)
System.err.println("exit value was non-zero");
// close stream
br.close();
// return list of strings to caller
return (String[])list.toArray(new String[0]);
public static void main(String[] args) throws Exception
try
FileWriter f1=new FileWriter("list1.txt");
String[] s = runCommand("arp -a");
for (int i = 0; i< s.length; i++)
f1.write(s);
System.out.println(s[i]);
f1.close();
}catch (Exception ex) { System.out.println(ex);}
SAMPLE OUTPUT:
Interface: 172.16.3.1 on Interface 0x1000003
Internet Address Physical Address Type
172.16.3.4 00-00-e2-13-a9-e8 dynamic
172.16.3.6 00-00-e2-13-aa-0f dynamic
172.16.3.10 00-00-e2-13-ab-bb dynamic
172.16.3.12 00-00-e2-13-ab-93 dynamic
172.16.3.16 00-00-e2-13-37-b8 dynamic
172.16.3.17 00-00-e2-13-37-19 dynamic
172.16.3.18 00-00-e2-13-37-1d dynamic
172.16.3.19 00-00-e2-13-38-98 dynamic
172.16.3.22 00-00-e2-13-37-54 dynamic
172.16.3.23 00-00-e2-13-39-02 dynamic
172.16.3.24 00-00-e2-13-39-0f dynamic
172.16.3.26 00-00-e2-13-37-a5 dynamic
172.16.3.27 00-00-e2-13-37-0b dynamic
172.16.3.28 00-00-e2-13-37-12 dynamic
172.16.3.29 00-00-e2-13-39-15 dynamic
172.16.3.30 00-00-e2-13-38-af dynamic
172.16.3.31 00-00-e2-13-37-fe dynamic
172.16.3.32 00-00-e2-13-38-ff dynamic
172.16.3.34 00-00-e2-13-ab-c8 dynamic
172.16.3.37 00-00-e2-13-ab-67 dynamic
172.16.3.42 00-00-e2-13-ab-19 dynamic
PLS HELP ME OUT IN GETTING ONLY THE IPADDRESS IN FOR LOOP IN SERVER SOCKET PROGRAM TO INVOKE ALL CLIENT'S PROGRAM IN NETWORK.
PLS HELP ME!!!!!!!
ATTACH THE CODE!!!!!!!!!!!!Connecting to a client presumes that the client is waiting for a connection.
If that is the case I would suggest looking a java.net.Socket. -
Hello!
I have a problem regarding server socket, i wrote a simple server socket program which would accept a socket then write through the DataOutputStream, using writeByte and read through the DataInputStream using readUnsignedByte.
My server socket is a java program, and the client was created using other language (which i do not know what language but it is already existing..).
My concern is that when I try to listen (in the server side), i would accept the socket, and the connection would now be established. BUT, whenever i would close my streams (input and output stream), the client socket I accepted and the ACTUAL server socket, the client is still connected. That's why whenever i would open my Server Socket, i would no longer receive any socket.. why is it like that..?
Can anyone help me..? Please do so.. I would appreciate your immediate reply..
Thanks a lot!
RonHI,
What you need in the client app is for it to listen for a CLOSE message like this (java code but the logic is there)
String fromServer ;
while(( fromServer = in.readLine()) != null )
System.out.println( "Server: " + fromServer ) ;
if( fromServer.equals("Closing down")) //checks all the time for the CLOSE signal !
break ;
// other stuff
out.close() ; // close the client end of the socket on the signal !
in.close() ;
You say the client app is already written. Well look in the specs and see what the CLOSE signal is.
There MUST be one or the client app doesn't work.
Hope that helps, -
Hi,
As the name of the forum suggests I am very new to this whole thing.
I am trying to write a client/server socket program that can encrypt and decrypt and has a GUI, can't use JCE or SSL or any built in encryption tools.
I have the code for everything cept the encryption part.
Any help, greatly appreciated,tnks a million but how do i incorporate that into the following client and server code:
here's the client code:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
class SocketClient extends JFrame
implements ActionListener {
JLabel text, clicked;
JButton button;
JPanel panel;
JTextField textField;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
SocketClient(){ //Begin Constructor
text = new JLabel("Text to send over socket:");
textField = new JTextField(20);
button = new JButton("Click Me");
button.addActionListener(this);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add("North", text);
panel.add("Center", textField);
panel.add("South", button);
} //End Constructor
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if(source == button){
//Send data over socket
String text = textField.getText();
out.println(text);
textField.setText(new String(""));
//Receive text from server
try{
String line = in.readLine();
System.out.println("Text received :" + line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
public void listenSocket(){
//Create socket connection
try{
socket = new Socket("HUGHESAN", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host: HUGHESAN.eng");
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
public static void main(String[] args){
SocketClient frame = new SocketClient();
frame.setTitle("Client Program");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
SERVER Code
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
class SocketServer extends JFrame
implements ActionListener {
JButton button;
JLabel label = new JLabel("Text received over socket:");
JPanel panel;
JTextArea textArea = new JTextArea();
ServerSocket server = null;
Socket client = null;
BufferedReader in = null;
PrintWriter out = null;
String line;
SocketServer(){ //Begin Constructor
button = new JButton("Click Me");
button.addActionListener(this);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add("North", label);
panel.add("Center", textArea);
panel.add("South", button);
} //End Constructor
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == button){
textArea.setText(line);
public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
try{
client = server.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
protected void finalize(){
//Clean up
try{
in.close();
out.close();
server.close();
} catch (IOException e) {
System.out.println("Could not close.");
System.exit(-1);
public static void main(String[] args){
SocketServer frame = new SocketServer();
frame.setTitle("Server Program");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
Again help on this is very welcomed -
Socket Programming-Not getting response from server.
Hi,
I am trying to communicate with server using java socket programming, I am getting the response for first two times third time when I am trying to write some thing I am not getting any response from the server,
I am writing to migrate the vb code to Java the vb is using a c++ dll to communicate with the server and we tried accessing the dll from java using JNI then it is working fine, this dll is dependent on windows so we want to avoid the dependency with windows that is why we are going for socket programming, Please help on this.Hi,
I am writing the data in forms of string
like
Socket sockt = new Socket(ipAddress, portNo);
out= new DataOutputStream(sockt.getOutputStream());
in = new DataInputStream(sockt.getInputStream());
out.writeBytes("Serv");
out.writeBytes("Serv,32");
out.writeBytes("home,serv32,run.prg,sucess");
these are the strings to communicate with server.
I am trying to read the same
StringBuffer buf = new StringBuffer();
byte b = '\0';
try {
while ((b = in.readByte()) != '\0')
char ch = (char) b;
buf.append(ch);
} catch (Exception e) {
System.out.println(e.getStackTrace());
we are getting the response for the first two strings, but for the third string it is getting stucked for some time and returing some junk values like '???' we are sending the same string using JNI and it is working. -
My first Server/Client Program .... in advise/help
Hello,
I am learning about Sockets and ServerSockets and how I can use the. I am trying to make the simplest server/client program possible just for my understanding before I go deper into it. I have written two programs. theserver.java and theclient.java the sere code looks like this....
import java.net.*;
import java.io.*;
import java.util.*;
public class theserver
public static void main(String[] args)
{ // IOReader r = new IOReader();
int prt = 3333;
BufferedReader in;
PrintWriter out;
ServerSocket serverSocket;
Socket clientSocket = null;
try{
serverSocket = new ServerSocket(prt); // creates the socket looking on prt (3333)
System.out.println("The Server is now running...");
while(true)
clientSocket = serverSocket.accept(); // accepts the connenction
clientSocket.getKeepAlive(); // keeps the connection alive
out = new PrintWriter(clientSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(in.ready())
System.out.println(in.readLine()); // print it
catch (IOException e) {
System.out.println("Accept failed:"+prt);
and the client looks like this
import java.net.*;
import java.io.*;
public class theclient
public static void main(String[] args)
BufferedReader in;
PrintWriter out;
IOReader r = new IOReader();
PrintWriter sender;
Socket sock;
try{
sock = new Socket("linuxcomp",3333); // creates a new connection with the server.
sock.setKeepAlive(true); // keeps the connection alive
System.out.println("Socket is connected"); // confirms socket is connected.
System.out.println("Please enter a String");
String bob = r.readS();
out = new PrintWriter(sock.getOutputStream(),true);
out.print(bob); // write bob to the server
catch(IOException e)
System.out.println("The socket is now disconnected..");
If you notice in the code I use a class I made called IOReader. All that class is, is a buffered reader for my System.in. (just makes it easier for me)
Ok now for my question:
When I run this program I run the server first then the client. I type "hello" into my system.in but on my server side, it prints "null" I can't figure out what I am doing wrong, if I am not converting correctly, or if the message is not ever being sent. I tried putting a while(in.read()) { System.out.println("whatever") } it never reaches a point where in.ready() == true. Kinda of agrivating. Because I am very new to sockets, I wanna aks if there is somthing wrong with my code, or if I am going about this process completely wrong. Thank you to how ever helps me,
Cobbwebhere's my simple server/client Socket :
Server:
import java.net.*;
import java.io.*;
public class server
public static void main(String a[])
ServerSocket server=null;
Socket socket=null;
DataInputStream input=null;
PrintStream output=null;
try
server=new ServerSocket(2000);
socket=server.accept();
input = new DataInputStream(socket.getInputStream());
output = new PrintStream(socket.getOutputStream());
//output.println("From Server: hello there!");
String msg="";
while((msg=input.readLine()) != null)
System.out.println("From Client: "+msg);
catch(IOException e)
catch(Exception e)
}Client:
import java.net.*;
import java.io.*;
public class client
static private Socket socket;
static private DataInputStream input;
static private PrintStream output;
public static void main(String a[])
try
socket=new Socket("10.243.21.101",2000);
System.out.println("\nconnected to: \""+socket.getInetAddress()+"\"");
input=new DataInputStream(socket.getInputStream());
output=new PrintStream(socket.getOutputStream());
output.println("From Client(Tux): "+a[0]);
String msg="";
//while((msg=input.readLine()) != null)
System.out.println("From Server(Bill): "+msg);
catch(java.io.IOException e)
catch(Exception e)
} -
HELP : Convert socket programming from Ipv4 to IPv6
Hi all,
I need help in converting my Ipv4 socket programing to Ipv6. How can I do this? I already have an Ipv4 socket programming that is working but when I tried to convert it to Ipv6 it doesn't work .
this is my Ipv4 socket programming :
DatagramPacket sendPacket;
DatagramSocket sock;
ip = jtfDIP.getText().trim();
try{
sock = new DatagramSocket();
add = InetAddress.getByName(ip);
sendPacket = new DatagramPacket(buf,buf.length,add,port);
Please help me. How can I convert this to Ipv6. Thank you.Socket sock = new Socket("host");
or
Socket sock = new Socket("192.168.1.1");
or
Socket sock = new Socket("www.host.com");
or
Socket sock = new Socket("hhhh.hhhh.hhhh.hhhh");
Get it? Just use whatever host, domain name, or IP you need, the underlying native code does the work - you'll never need to do anything, for the most part. -
Help needed with swings for socket Programming
Im working on a Project for my MScIT on Distributed Computing...which involves socket programming(UDP)....im working on some algorithms like Token Ring, Message Passing interface, Byzantine, Clock Syncronisation...i hav almost finished working on these algorithms...but now i wanna give a good look to my programs..using swings but im very new to swings...so can anyone help me with some examples involving swings with socket programming...any reference...any help would be appreciated...please help im running out of time..
thanking u in advance
anDyhi im Anand(AnDY),
i hav lost my AnDY account..plz reply to this topic keeping me in mind :p -
Desperately need some help with client-server java programming
Hi all,
I'm new to client server java programming. I would like to work on servlets and apache tomcat. I installed the apache tomcat v 5.5 into my machine and i have sun java 6 also. I created a java applet class to be as a client and embed it into an html index file, like this:
<applet code="EchoApplet.class" width="300" height="300"></applet>However, when I try to run the html file on the localhost, it print this error: classNotFoundException, couldn't load "EchoApplet.class" class. On the other hand, when I open the index file on applet viewer or by right clicking, open with firefox version 3, it works.
I thought that the problem is with firefox, but after running the applet through the directory not the server, i found that the problem is not any more with firefox.
Can anyone help me to solve this problem. I'm working on it for 5 days now and nothing on the net helped me. I tried a lot of solutions.
Any help?arun,
If the browser is going to execute $myApplet, first it must get the $myApplet.class from the server, right?
So it follows that:
1. $myApplet.class must be acessible to server, and
2. the server must know exactly where to find $myApplet.class
So, the simplest solution is to is put the $myApplet.class in the same directory as the HTML file which uses it... then your applet tag is simple:
<applet height="200" width="400" code="$myApplet.class" ></applet>* The height & width attributes are required
* Note the +.class+ is required in the code attribute (a common mistake).
* This works uniformly (AFAIK) accross all java-enabled browsers.
* There are incompatibilities with the codebase attribute. Poo!
Cheers. Keith. -
Need help with java.nio.socket program.
Can someone please help me here? I am trying to create a class that listens on a socket for an incoming connection, but I am getting the following error on compile:
SocketIn.java:48: incompatible types
found : java.nio.channels.SocketChannel
required: java.net.Socket
Socket requestSocket = requestChannel.accept();
Here is my code:
package NETC;
import java.net.*;
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
public class SocketIn{
// Buffer for any incoming data.
private static ByteBuffer inBuffer = ByteBuffer.allocateDirect(1024);
CharBuffer charBuffer = null;
public SocketIn(int intPort)throws Exception{
// Create a non-blocking server socket.
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
// Use the host and port to bind the server socket.
InetAddress inetAddress = InetAddress.getLocalHost();
InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, intPort);
serverChannel.socket().bind(socketAddress);
// The selector for incoming requests.
Selector requestSelector = SelectorProvider.provider().openSelector();
// Put the server socket on the selectors 'ready list'.
serverChannel.register(requestSelector, SelectionKey.OP_ACCEPT);
while(requestSelector.select() > 0){
System.out.println("Connection Accepted...");
// A request has been made and is ready for IO.
Set requestKeys = requestSelector.selectedKeys();
Iterator iterator = requestKeys.iterator();
while(iterator.hasNext()){
SelectionKey requestKey = (SelectionKey)iterator.next();
// Get the socket that's ready for IO.
ServerSocketChannel requestChannel = (ServerSocketChannel)requestKey.channel();
// This shouldn't block.
Socket requestSocket = requestChannel.accept();
inBuffer.clear();
requestSocket.read(inBuffer);
inBuffer.flip();
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
charBuffer = decoder.decode(inBuffer);
iterator.remove();
}Well its been about a month and a half so I guess you have your answer. In case you don't...
// This shouldn't block.
Socket requestSocket = requestChannel.accept();
The problem is quite simple. The ServerSocketChannel.accept() returns a SocketChannel. (Channel -> Channel).
You can get access to the socket using the SocketChannel.
SocketChannel requestSocketChannel = requestChannel.accept();
Socket requestSocket = requestSocketChannel.socket();
But you don't need the socket to read and write.
Maybe you are looking for
-
HELP, My SWF doesn´t work in latest versions of IE and Safari
I have a swf made in Flash CS4. It works fine in firefox and older versions of flash player in IE, but it doesn't work in recent versions of IE and Safari In this case just I can hear the music. Could help me please, my URL is: http://www.quecolor.co
-
Can C4480 ink be used for F4480
Hi, I have a hp deskjet F4480 printer. I bought a c4480 ink, can it be used for my F4480 printer? regards Peter This question was solved. View Solution.
-
Best way to export custom postcard as .jpeg
Hi! I am very new to photoshop, and, I am sure these are very elementary questions... please bear with me. I really appreciate your help. I created a custom postcard with layers - a collage of family photos - to use as a Christmas postcard. After rea
-
CDMC - Function Modules not Found
Hi, Initially the Solution manager ST level is 23 and CDMC clearning analysis worked will with ERP satellite system. Later, Solution manager has upgraded with 24 and not able to actiavate the statistics and unable to perform clearning analysis. Below
-
Moving a project from FCP 10.0 to 10.1
Was just asked to colour grade a 2 hour show edited in the earlier FCPX 10.01 (Brazil). I want to import that whole project into FCPX 10.1.1. Where might I find the particular protocol (or maybe a tutorial even) for importing the earlier version pro