Multiple Clients in Client/Server Program
I'm currently trying to make a small Client/Server application that will mimic a very basic chat room program. The basic idea is that the Server side of the program is started and multiple Client programs can connect and communicate with each other. However, I'm having a few problems at the moment, mostly with figuring out how it can work.
Firstly, I can communicate one to one with the server and the client as the client socket is stored in a variable. However, to make it possible to allow multiple connections I've used a thread for each new connection but I'm not sure how I can broadcast messages to every connection. Would it be safe enough to store each client socket in a list and then communicate that way? Not sure what will happen when the client disconnects though it seems to be an issue.
I'm also not sure how every message can be broadcasted to every single connections to the server. The server program can send a message to every client but the clients message at the moment only goes to the server. Anyway here's a bit of my code so far:
SwingWorker<Socket, Void> worker = new SwingWorker<Socket, Void>() {
protected Socket doInBackground() throws Exception {
// Client socket
try {
while (!stopRequested) {
clientSocket = serverSocket.accept();
// Stop requested is checked twice because the accept() method
// waits for a connection
if (!stopRequested) {
HostFrame.getFeedbackTextArea().append("New Connection Found");
Thread clientThread = new HandlerThread(clientSocket);
clientThread.start();
else {
serverSocket.close();
clientSocket.close();
catch (Exception e) {
HostFrame.getFeedbackTextArea().append("Failed to Connect with Client");
System.out.println(e.getMessage());
return clientSocket;
};The SwingWorker is used so that the GUI doesn't freeze when the server tries to find a connection. At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client. Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets. Any help would be much appreciated
clientSocket = serverSocket.accept();'clientSocket' should be a local variable here.
else {
serverSocket.close();
clientSocket.close();You shouldn't close 'clientSocket here'. All you're accomplishing is closing the most recently accepted client socket. What about the others? Generally speaking you should let the client-handling threads take care of their own sockets completely.
return clientSocket;This return statement is meaningless. You may as well return null. SwingWorker doesn't care. Don't just return something because you've got it lying around. In this case you shouldn't have it lying around.
At the moment it just creates a thread for each new connection but I'm guessing this isn't what I'm going to be needing to handle more than one client.That is exactly what you have to do to handle more than one client. Once you fix it as per above.
Also at the moment I have no way of directing a message to a specific socket I'm pretty much just using the standard method shown on the Sun website about Sockets.You probably need to keep a Map of client sockets accepted, keyed by some client identifier.
Similar Messages
-
Runtime exception in a multiple file sending client server program ?
hi I have the following program for one client and one server.
import java.io.*;
public class FileTransferRoutines{
private int BUFFER = 2048;
private String LastFileRecieved;
private long sendRestart;
private long recieveRestart;
public void setSendBufferSize(int size)
BUFFER = size;
public void setRecieveBufferSize(int size)
BUFFER = size;
public void storeRawStream(DataInputStream in, String tempDir, long restart) {
try {
RandomAccessFile fileOut;
int fileCount = in.readInt();
for(int i=0; i<fileCount; i++) {
byte data[] = new byte[BUFFER];
String fileName = in.readUTF();
fileOut = new RandomAccessFile(tempDir+"\\"+fileName,"rws");
long fileLength = in.readLong();
if(i==0 && restart != 0)
fileOut.seek(restart);
long base = restart/(long)BUFFER;
long offset = restart - base*(long)BUFFER;
for(int j=(int)base; j<fileLength / BUFFER; j++) {
int totalCount = 0;
if(j==(int)base)
totalCount = (int)offset;
while(totalCount < BUFFER) {
int count = in.read(data, totalCount, BUFFER - totalCount);
totalCount += count;
recieveRestart += (long)count;
fileOut.write(data, 0, totalCount);
else
for(int j=0; j<fileLength / BUFFER; j++) {
int totalCount = 0;
while(totalCount < BUFFER) {
int count = in.read(data, totalCount, BUFFER - totalCount);
totalCount += count;
recieveRestart +=(long)count;
fileOut.write(data, 0, totalCount);
// read the remaining bytes
int count = in.read(data, 0, (int) (fileLength % BUFFER));
recieveRestart += (long)count;
fileOut.write(data, 0, count);
fileOut.close();
LastFileRecieved = fileName;
recieveRestart = 0;
} catch (Exception ex) {
ex.printStackTrace();
private File[] makeFileList(String TempDir)
File dir = new File(TempDir);
File files[];
files = dir.listFiles();
return files;
public void sendFiles(String dir, DataOutputStream out,
String lastFileSent, long restart) throws IOException {
byte data[] = new byte[BUFFER];
File files[] = makeFileList(dir);
RandomAccessFile fileInput;
if(lastFileSent == null)
out.writeInt(files.length);
for(int i=0; i<files.length; i++) {
// send the file name
out.writeUTF(files.getName());
// send the file length
out.writeLong(files[i].length());
fileInput = new RandomAccessFile(files[i],"r");
int count = 0;
while((count = fileInput.read(data) )!= -1) {
out.write(data, 0, count);
sendRestart = sendRestart + (long)count;
fileInput.close();
sendRestart = 0;
else{
int lastFileIndex = 0;
for(int j=0 ; j<files.length; j++){
if(lastFileSent.equals(files[j].getName()))
lastFileIndex = j;
out.writeInt(files.length-lastFileIndex);
for(int i=lastFileIndex+1; i<files.length; i++) {
// send the file name
out.writeUTF(files[i].getName());
// send the file length
out.writeLong(files[i].length());
fileInput = new RandomAccessFile(files[i],"r");
if(i==lastFileIndex+1)
fileInput.seek(restart);
int count = 0;
while((count = fileInput.read(data)) != -1) {
out.write(data, 0, count);
sendRestart = sendRestart + (long)count;
fileInput.close();
sendRestart = 0;
out.flush();
public long getRecieveRestart()
return recieveRestart;
public long getSendRestart()
return sendRestart;
public String getLastFileRecieved()
return LastFileRecieved;
public void setRecieveRestart(long value)
recieveRestart = value;
public void setSendRestart(long value)
sendRestart = value;
import java.io.*;
import java.net.*;
public class TransferServer implements Runnable {
private int serverPort;
private volatile boolean closeServer = false ;
private volatile boolean fileSend = false;
private volatile boolean directorySend = false;
private volatile long sendRestart = 0;
private volatile String fileName = null;
private volatile String dirName = null;
private volatile String lastFileSent = null;
private volatile FileTransfer ftp;
//private volatile FileTransferRoutines ftrp;
private ServerSocket server;
TransferServer(int port)
serverPort = port;
try{
server = new ServerSocket(serverPort);
}catch(IOException ioe)
ioe.printStackTrace();
ftp = new FileTransfer();
//ftrp = new FileTransferRoutines();
public void closeConnection()
closeServer = true;
public void setSendRestart(long restart)
ftp.setSendRestart(restart);
sendRestart = restart;
public void setFileToSend(String FileName)
clearDirectoryToSend();
fileSend = true;
fileName = FileName;
public void clearFileToSend()
fileSend = false;
fileName = null;
public void setDirectoryToSend(String DirName)
clearFileToSend();
directorySend = true;
dirName = DirName;
public void clearDirectoryToSend()
directorySend = false;
dirName = null;
public void setLastFileSent(String fileName)
lastFileSent = fileName;
public void run()
Socket sock;
try{
while(!closeServer)
sock = server.accept();
try{
if(fileSend && !directorySend)
RandomAccessFile raf = new RandomAccessFile(fileName , "r");
ftp.sendFile(raf,sock.getOutputStream(),sendRestart);
ftp.setSendRestart(0);
sendRestart = 0;
sock.close();
clearFileToSend();
else if(directorySend && !fileSend)
DataOutputStream dout = new DataOutputStream(sock.getOutputStream());
FileTransferRoutines ftrp = new FileTransferRoutines();
ftrp.setSendBufferSize(sock.getSendBufferSize());
long restart = ftrp.getSendRestart();
ftrp.sendFiles(dirName,dout,lastFileSent,restart);
sock.close();
clearDirectoryToSend();
}else
sock.close();
catch(FileNotFoundException foe)
foe.printStackTrace();
catch(IOException ioe)
ioe.printStackTrace();
}catch(IOException ioe)
ioe.printStackTrace();
public class TransferServerTest {
public static void main(String[] args) {
TransferServer ttc = new TransferServer(4444);
ttc.setDirectoryToSend("C:\\testFolder\\folder1\\");
Thread fileTransferServer = new Thread(ttc,"fileserver");
fileTransferServer.start();
import java.io.*;
import java.net.*;
public class TransferClient {
public static void main(String[] args) {
String dir = "C:\\testFolder\\folder2\\";
Socket sock = null;
try{
sock = new Socket("localhost",4444);
}catch(IOException ioe)
System.out.println("Could not connect to server");
try{
FileTransferRoutines ftrp = new FileTransferRoutines();
ftrp.setRecieveBufferSize(sock.getReceiveBufferSize());
DataInputStream din = new DataInputStream(sock.getInputStream());
ftrp.storeRawStream(din,dir,0);
}catch(IOException ioe)
ioe.printStackTrace();
this code works fine for the first connection of the client The client then automatically disconnects after the transfer is complete.
when i reconnect the client by rerunning the TransferClient code
it gives the following exception java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at FileTransferRoutines.storeRawStream(FileTransferRoutines.java:24)
at TransferClient.main(TransferClient.java:19)
i just cant understand where that eof comes from
please help!!!!
Edited by: danish.ahmed.lnmiit on Jan 21, 2008 7:18 PMi was not closing my DataInputStream and also cleaned up my code and problem got solved
-
Problem with program hanging randomly on certain commands from win 7 pro client to SB Server
Having a problem with program hanging randomly on certain commands from Win-7 Pro Client to SB Server Both 64-Bit
Five other slower XP-Pro 32 Bit systems though they are older and slower systems do not seem to hang as readily if at all.
It has been very frustrating as the Client-System, SB-Server and Program should work w/o any hitches, but this seems to work fine @ times and then hang randomly.
Would appreciate any and all suggestions in assisting.... JimBAgde-MSSYou can try this, as I have had similar problems with another MS Access .MDB file and slow access before. This fixed my problem for me. On the slow computer, make sure the program is set to see the .mdb file via UNC path, not a mapped drive letter. ex.
USE: \\yourserver\shared\dental\file.mdb
DO NOT: S:\\shared\dental\file.mdb
hope this helps -
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. -
Related to Network program using Java Client and C server
I am little bit experience in java technology. I need an urgent help as I have to submit a document related to C server and Java client. But while searching in net i cant get a proper guidance for C server as many errors thrown in sys/socket.h and other new header files. Can any one help me out for giving source code for C Server. so that i can further involve in that document. Please help me out. i am really helpless by the way the C server thrown error. after finishing that C server only i can concentrate on Java client...
Hai Josah,
Thanks for your reply.. I have gone through many sockets server program in C but the real proble is the header file they include like
socket.h and in.h etc.. they also provide these header files but if we compile in turboC they inturn require some other header files. I dont get the full hierarchy of C server program. I found some help in Java programming Archive about C Server and java client. As i am new to C i cant get the full header files for the server.c if i complete taht only i can proceed to java client. If u can redirect me for any good C sites also i can be thankful for u forever..please -
HTTP Client/Server program problems
Hi all,
I am doing an exercise in which I create a Client and Server program. I send a GET request but nothing seems to happen. There is obviously something I'm missing. Could it be a badly formed request? The code is below. Any help is appreciated.
Client program.....
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class HTTPClient{
String host, path;
int port;
public static void main (String argv[]){
new HTTPClient(argv[0]);
public HTTPClient(String url){
try{
URL myURL = new URL(url);
host = myURL.getHost();
port = myURL.getPort();
System.out.println("Port = " + port);
if (port == -1) port = 30280;;
path = myURL.getPath();
if (path.equals("")) path = "/";
Socket s = new Socket(InetAddress.getByName(host), port);
sendRequest(s.getOutputStream());
printResponse(s.getInputStream());
s.close();
catch(MalformedURLException murl){
System.out.println("Badly formatted URL " + murl.getMessage());
catch(IOException e){
System.out.println("Problem initialising socket " + e.getMessage());
public void sendRequest(OutputStream out){
StringBuffer buf = new StringBuffer();
buf.append("GET /AC095.html HTTP/1.1\r\n");
buf.append("Host: http://students.odl.qmul.ac.uk\r\n\r\n");
try{
out.write(buf.toString().getBytes("US-ASCII"));
catch (IOException e) {System.out.println(e.getMessage());
public void printResponse(InputStream in){
try{
while (in.available() <= 0)
Thread.sleep(500);
while (in.available() > 0)
System.out.print((char) in.read());
System.out.println ("");
catch (IOException e) {
System.out.println(e.getMessage());
catch (InterruptedException ie) {
System.out.println("Error waiting for response " + ie.getMessage());
/* Read in the response from the HTTP server and print it out */
}Server code......
import java.io.*;
import java.net.*;
import java.util.*;
public class HTTPServer{
String version = null;
public String httpVer;
public static void main(String argv[]){
new HTTPServer(Integer.parseInt(argv[0]));
public HTTPServer(int port){
boolean listening = true;
try{
ServerSocket ss = new ServerSocket(port);
System.out.println("HTTP Server running and listening for requests...");
while (listening){
Socket mySocket = ss.accept();
InputStream in = mySocket.getInputStream();
readHeaders(in);
String response = getResponse();
OutputStream out = mySocket.getOutputStream();
out.write(response.getBytes("US-ASCII"));
out.flush();
mySocket.close();
catch(Exception e){System.out.println(e.getMessage());}
private String getResponse(){
StringBuffer responseBuf = new StringBuffer();
responseBuf.append (httpVer + " 200 OK\r\n");
responseBuf.append ("Content-type: text/html\r\n");
responseBuf.append ("Content-length: 119\r\n");
responseBuf.append ("<HTML>\r\n");
responseBuf.append ("<TITLE> My served web document </TITLE>\r\n");
responseBuf.append ("</HEAD>\r\n");
responseBuf.append ("<BODY>\r\n");
responseBuf.append ("<H1> Hello from the server! </H1>\r\n");
responseBuf.append ("</BODY>\r\n");
responseBuf.append ("</HTML>\r\n\r\n");
String responseStr = responseBuf.toString();
responseStr = responseStr.trim();
return "";
private void readHeaders(InputStream in) throws IOException {
StringBuffer sbuf = new StringBuffer();
int ch;
String clientStr;
//This loop reads in all of the input until there is nothing left to read.
//All of the characters are appended to the string buffer.
while ((ch = in.read()) != -1) {
sbuf.append((char) ch);
//clientStr will hold string in string buffer without any leading or
//trailing white space.
clientStr = sbuf.toString();
clientStr = clientStr.trim();
//Split clientStr into substrings and store them in an array.
String [] tokens = clientStr.split(" ");
//Obtains HTTP version
httpVer = tokens [2];
}Cheers,
ChrisI've written out.flush() in the server program. When I attempt to connect to the server it just hangs. I've modified the code locally to request a webpage from elsewhere and it works so it can't be the format of my GET request. I assume that the problem has to be in the Server program. Is it not reading in and understanding the /r/n properly?
-
File transfer, read write through sockets in client server programming java
Hello All, need help again.
I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
Client side
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class XMLSocketC
public static void main(String[] args) throws IOException
//Establish a connection to socket
Socket toServer = null;
String host = "127.0.0.1";
int port = 4444;
try
toServer = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to host.");
System.exit(1);
//Send file over Socket
//===========================================================
BufferedInputStream fileIn = null;
BufferedOutputStream out = null;
// File to be send over the socket.
File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
// Checking for the file to be sent.
if (!file.exists())
System.out.println("File doesn't exist");
System.exit(0);
try
// InputStream to read the file
fileIn = new BufferedInputStream(new FileInputStream(file));
}catch(IOException eee)
System.out.println("Problem, kunne ikke lage fil");
try
InetAddress adressen = InetAddress.getByName(host);
try
System.out.println("Establishing Socket Connection");
// Opening Socket
Socket s = new Socket(adressen, port);
System.out.println("Socket is clear and available.....");
// OutputStream to socket
out = new BufferedOutputStream(s.getOutputStream());
byte[] buffer = new byte[1024];
int numRead;
//Checking if bytes available to read to the buffer.
while( (numRead = fileIn.read(buffer)) >= 0)
// Writes bytes to Output Stream from 0 to total number of bytes
out.write(buffer, 0, numRead);
// Flush - send file
out.flush();
// close OutputStream
out.close();
// close InputStrean
fileIn.close();
}catch (IOException e)
}catch(UnknownHostException e)
System.err.println(e);
//===========================================================
//Retrieve data from Socket.
//BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
//String fromServer;
//Read from the server and prints.
//Receive text from server
FileWriter fr = null;
String frn = "xxx_response.xml";
try {
fr = new FileWriter(frn);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
try{
String line = in.readUTF(); //.readLine();
System.out.println("Text received :" + line);
fr.write(line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
in.close();
toServer.close();
public class XMLSocketS
public static void main(String[] args) throws IOException
//Establish a connection to socket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
Socket clientLink = null;
while (true)
try
clientLink = serverSocket.accept();
System.out.println("Server accepts");
BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
byte[] buff = new byte[1024];
int readMe;
while( (readMe = inn.read(buff)) >= 0)
{ //reads from input stream, writes the file to disk
ut.write(buff, 0, readMe);
// close the link to client
clientLink.close();
// close InputStream
inn.close();
// flush
ut.flush();
// close OutputStream
ut.close();
//Sending response to client
//============================================================
//============================================================
System.out.println("File received");
}catch(IOException ex)
{System.out.println("Exception.");}
finally
try
if (clientLink != null) clientLink.close();
}catch(IOException e) {}
clientLink.close();
//serverSocket.close();
}SERVER
import java.net.*;
import java.io.*;
public class XMLSocketS
public static void main(String[] args) throws IOException
//Establish a connection to socket
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4545);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
Socket clientLink = null;
try
clientLink = serverSocket.accept();
System.out.println("Server accepts the client request.....");
BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
byte[] buff = new byte[1024];
int readMe;
while( (readMe = inn.read(buff)) >= 0)
{ //reads from input stream, writes the file to disk
ut.write(buff, 0, readMe);
ut.flush();
//Sending response to client
//============================================================
BufferedInputStream ftoC = null;
BufferedOutputStream outtoC = null;
// File to be send over the socket.
File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
try
// InputStream to read the file
ftoC = new BufferedInputStream(new FileInputStream(file));
}catch(IOException eee)
{System.out.println("Problem reading file");}
// OutputStream to socket
outtoC = new BufferedOutputStream(clientLink.getOutputStream());
byte[] buffer = new byte[1024];
int noRead;
//Checking if bytes available to read to the buffer.
while( (noRead = ftoC.read(buffer)) >= 0)
// Writes bytes to Output Stream from 0 to total number of bytes
outtoC.write(buffer, 0, noRead);
outtoC.flush();
//============================================================
System.out.println("File received");
}catch(IOException ex)
{System.out.println("Exception.");}
finally
try
if (clientLink != null) clientLink.close();
}catch(IOException e) {}
clientLink.close();
//serverSocket.close();
}CLIENT SIDE
import java.io.*;
import java.net.*;
public class XMLSocketC
@SuppressWarnings("deprecation")
public static void main(String[] args)
// Server: "localhost" here. And port to connect is 4545.
String host = "127.0.0.1";
int port = 4545;
BufferedInputStream fileIn = null;
BufferedOutputStream out = null;
// File to be send over the socket.
File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
try
// InputStream to read the file
fileIn = new BufferedInputStream(new FileInputStream(file));
}catch(IOException eee)
{System.out.println("Problem");}
try
System.out.println("Establishing Socket Connection");
// Opening Socket
Socket clientSocket = new Socket(host, port);
System.out.println("Socket is clear and available.....");
// OutputStream to socket
out = new BufferedOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[1024];
int numRead;
//Checking if bytes available to read to the buffer.
while( (numRead = fileIn.read(buffer)) >= 0)
// Writes bytes to Output Stream from 0 to total number of bytes
out.write(buffer, 0, numRead);
// Flush - send file
out.flush();
//=======================================
DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
String str;
while(!(str = in.readLine()).equals("EOF")) {
System.out.println("client : Read line -> <" + str + ">");
outf.write(str);//Write out a string to the file
outf.newLine();//write a new line to the file (for better format)
outf.flush();
//=======================================
// close OutputStream
out.close();
// close InputStrean
fileIn.close();
// close Socket
clientSocket.close();
}catch (IOException e)
{System.out.println("Exception.");}
Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
Thanks -
Can I put both RMI server and client in a same program
hi everybody...
I wanna know that can I use RMI server and client in a same program....My idea is like that I wanna use the same program for client and server....When I open my program, I can accept connection from other program and if I want to connect to others, I can also connect it. I expect you to understand my question. Here are the sample code for my program...
package Chat.Rmi;
import java.lang.*;
import java.util.*;
import java.rmi.*;
import javax.swing.*;
import java.net.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class netKitManager implements netKitInterface{
public netKitManager(){
try{
reg = LocateRegistry.createRegistry(4242);
reg.rebind("NetKitServer",this);
}catch(RemoteException re){
public void DirectConnect(String ip){
try{
netUser = (netKitInterface) Naming.lookup("rmi://"+ip+":4242/NetKitServer");
JOptionPane.showMessageDialog(null,"Connection succeded!");
}catch(NotBoundException nbe){
JOptionPane.showMessageDialog(null,"There is no server at specified IP address!");
}catch(MalformedURLException mue){
JOptionPane.showMessageDialog(null,"IP adress may be wrong!");
}catch(RemoteException re){
JOptionPane.showMessageDialog(null,"Remote exception occured!");
public void SendMessage(String msg){
try{
netUser.SetMessage(msg);
}catch(RemoteException re){
public void SetMessage(String msg) throws RemoteException{
chatKit.SetMessage(msg);
private netKitInterface netUser;
private Hashtable netUserList;
private Registry reg;
}Yes it can be done. I have done it.
-
Client/server program: Urgent, pls help!!
I am new to Java, particularly Networking in Java, while writing client/server application I have got completely strucked now. Can any one give me an idea where I am wrong?
I am writing a simple client server application in Java using Socket and ServerSocket classes as a part of my course work. Through client I am just establishing connection with server, getting user inputs/commands, sending the same input to server (server will capitalize this input and return it back to client), receiving and displaying server�s response.
The connection is established fine. Even it is accepting users input well but I am getting runtime NullPointerException while trying to send it to server. Here is the working of my client command window.
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>javac TClient.java
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>java TClient
Enter the message
hello
Exception in thread "main" java.lang.NullPointerException
at TClient.Send_Message(TClient.java:46)
at TClient.main(TClient.java:76)
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>
As soon as I get this exception the connection with server is lost and I get this in server command window.
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>javac TCPServer.java
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>java TCPServer
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java
:2150)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream
.java:2163)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputS
tream.java:2631)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:734
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:253)
at TCPServer.main(TCPServer.java:17)
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>
Here is my code for server (TCPServer.java)
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(80);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
ObjectInputStream inFromClient = new ObjectInputStream(connectionSocket.getInputStream());
ObjectOutputStream outToClient =
new ObjectOutputStream(connectionSocket.getOutputStream());
clientSentence = (String ) inFromClient.readObject();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeObject(capitalizedSentence);
And this is for Client (TClient.java)
import java.io.*;
import java.net.*;
import java.util.*;
class TClient {
private ObjectOutputStream server_output;
private ObjectInputStream server_input;
private Socket client;
private void server_connect() throws IOException
client = new Socket(InetAddress.getLocalHost(), 80);
private void getstreams() throws IOException
server_output = new ObjectOutputStream (client.getOutputStream());
server_output.flush();
server_input = new ObjectInputStream(client.getInputStream());
private String get_cmd_frm_usr() throws IOException
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
String sentence;
System.out.println("Enter the message");
sentence = inFromUser.readLine();
/*StringTokenizer st = new StringTokenizer(sentence);
while (st.hasMoreTokens()) //separating n printing words of inputted sentence
System.out.println(st.nextToken());
return(sentence);
private void Send_Message(String msg) throws IOException
//System.out.println("within send_message method :"+ msg);
server_output.writeObject( msg );
server_output.flush();
private void recieve_n_disp_mess() throws Exception
String modifiedSentence;
modifiedSentence = ( String ) server_input.readObject();
System.out.println("\n\n by SERVER: " + modifiedSentence);
private void close_connection() throws IOException
client.close();
public static void main(String args[]) throws Exception
TClient client = new TClient();
try{
client.server_connect();
String command=client.get_cmd_frm_usr();
//System.out.println("this is returned from input method n ready to sent to server soon: "+ command);
client.Send_Message(command);
client.recieve_n_disp_mess();
client.close_connection();
} catch(EOFException eofException) {}
catch (IOException ioException) {}you never initialized the server_output and the server_input vriables...
I see you have the getstreams() function which should initialize them but you never call it...
so untill you will call it those variables will stay null.
I can also see you do not implement constructors, its much easier just to implement these instead of functions initializing variables...
Hope it will help
private void getstreams() throws IOException
server_output = new ObjectOutputStream
(client.getOutputStream());
server_output.flush();
server_input = new
ObjectInputStream(client.getInputStream());
public static void main(String args[]) throws
Exception
TClient client = new TClient();
try{
client.server_connect();
String command=client.get_cmd_frm_usr();
//System.out.println("this is returned from input method n ready to sent to server soon: "+ command);
client.Send_Message(command);
client.recieve_n_disp_mess();
client.close_connection();
} catch(EOFException eofException) {}
catch (IOException ioException) {} -
Purpose of Multiple Clients in Development Server
can anybody tell me the advantages and
disadvantages of having multiple clients in a
development server?I don't think there is disadvantage when we have multiple clients for development system
DEV SAP system may have multiple clients..
Main pupose : Changes can be client dependent or client independent
Client-independent effects some clients.
Client-dependent effects all clients.
Let me say one example : Dev system has two clients
100 - Here we can write the code
200 - Testing will be here ( customizing will done here)
http://help.sap.com/saphelp_nw04/helpdata/en/8d/933d3c3a926614e10000000a11402f/frameset.htm
http://www.sap-img.com/general/what-is-sap--landscape.htm
http://help.sap.com/saphelp_nw2004s/helpdata/en/96/8a99386185c064e10000009b38f8cf/content.htm
Thanks
Seshu -
To:NOAH:REGARDING CLIENT/SERVER Program
Dear Noah,,,how to run the server program since there is no component inside?Pls reply
Noah.
can u pls send the client porgram so i can run the program and see.Got one point i still doesn;t understand
which is jdk only allow user to run JAVAC *.java one time
if i run the server ,how could i run the client? -
Handle Received data of Multiple TCP clients on TCP Server by displaying them into Datagrid
Hello All,
I have developed a C# based TCP server GUI application which is accepting the data from multiple TCP clients on TCP server.
The data i am receiving from TCP clients is a 32 bit data. In my application multiple TCP client data goes like this:
00012331100025123000124510321562
01112563110002512456012451032125 and so on...
Now i want those data of the TCP clients to be parsed into 4 bits first and display it in 8 columns (32/4=8) of (say) datagrid as each 4 bit represents some characteristics of the TCP client. The same thing
should work for next TCP client on second row of datagrid.
Can you give me some suggestion or an example how to go about this? Any help would be appreciated.
Thank you in advance.
Here is my code for receiving data from multiple TCP clients.
void m_Terminal_MessageRecived(Socket socket, byte[] buffer)
string message = ConvertBytesToString(buffer, buffer.Length);
PublishMessage(listMessages, string.Format("Sockets: {0}", message));
// Send Echo
// m_ServerTerminal.DistributeMessage(buffer);
private string ConvertBytesToString(byte[] bytes, int iRx)
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
d.GetChars(bytes, 0, iRx, chars, 0);
string szData = new string(chars);
return szData;Now i want those data of the TCP clients to be parsed into 4 bits first and display it in 8 columns (32/4=8) of (say) datagrid as each 4 bit represents some characteristics of the TCP client. The same thing
should work for next TCP client on second row of datagrid
If mean it's a Windows Forms application and you want to display those bits in a DataGridView control, then please see these threads:
Add row to datagridview
Programmatically add new row to DataGridView
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Hi;
I want to learn client server programming on using windows xp for the client and windows server 2003.
I downloaded the 9.2 windows xp database version for the client . What do I need to download for the server? I see that there is a 32 and 64 bit version for the server.
Thanks for your help!What I was asking is what should I install on the server
the 32 or 64 bit version of oracle?
I want to learn how to write client/server programs using Oracle.
I have a network at home with one computer serving as the client and another has server 2003 on it.
Again Thanks for your help! -
Client Server program using Applets for client
Creating a client server program using Applets for the clients.
Having problems distrubting the message from client to client
using ObjectOutputStreams/ObjectInputSteams.
I can connect each client to simple server and respond with by writting
the i/o stream of each client but unable to communicate from client to client. If any one out there has in tips of creating a class of objectOutputStreams that holds a array of ObjectOutputStreams and then broadcasts the message to every client, it would be much appreciated
Thanks.Cheers poop for your reply
I never explained the problem properly. What it is I am trying to set up a Client Server program using Applets as the clients GUI. The problem is broadcasting the message to multiply client connnection(s).
Below is code, each client can connect and send message to the server. The problems is broadcasting the message to every client connection. The every client can input a message but only the last connected client can receive the message?????? Thanks in advance..
/*this my server class */
import java.io.*;
import java.net.*;
public class Server extends JFrame
private static final int ServerPort=8080;
private static final int MaxClients=10;
private ObjectOutputStream output=null;
private ObjectInputStream input=null;
private BroadCastMessage broadcastMessage;
public void runServer()
BroadCastMessage broadcastMessage= new BroadCastMessage();
try
{ //connect to server
ServerSocket s = new ServerSocket(ServerPort,MaxClients);
//listen to port 5000 for new connections
///max is 25
System.out.println("Server listening on port "+ServerPort);
while (state.isProgramRunning())
try
/// sGUI.waitForConnection();//new line
s.setSoTimeout(100);
//enable times in server-socket
while (true)
Socket incoming = s.accept();
//wait and accept connnections from serverSocket
//instance of the class,pases the new connection and message
//spawn as a thread
SocketConnection connection=new SocketConnection(incoming,broadcastMessage);
Thread a = new Thread(connection); a.start();
System.out.println(state.getConnectionCount()+"Connection received from :"+incoming.getInetAddress());
catch(InterruptedIOException x){}
while (state.getConnectionCount()>0);
System.exit(0);
}catch (IOException e){}
public static void main(String[] args)
Server s =new Server();
s.runServer();
/*this is my socket connection thread*/
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class SocketConnection implements Runnable
private ObjectOutputStream out;
private ObjectOutputStream output=null;
private ObjectInputStream input=null;
private BroadCastMessage passOnMessage;
private Socket theConnection=null;
private String Inmessage="";
private int Ocount;
public SocketConnection(Socket caller,BroadCastMessage broadcastMessage,Ocount)
theConnection =caller;///(5000,n)
Ocount=ncount;
passOnMessage=broadcastMessage;
public void run()
try
getStreams();
processConnection();
catch(Exception e)
{String clientDetails=("connection from IP Address: "+theConnection.getInetAddress());}
private synchronized void getStreams() throws IOException
{ //get streams to send and receive data
//set up output buffer to send header information
///Ocount++;
//create new objectoutputstream
output=passOnMessage.getOutputObject(output,theConnection,Ocount);
///flush output buffer to send header info.
Ocount++;
//set up input stream for objects
input =new ObjectInputStream(
theConnection.getInputStream());
System.out.print("\nGot I/O streams\n");
private synchronized void processConnection()throws IOException
//process connection with client
String Outmessage =" count : "+status.getConnectionCount();
//send connection successful message to client
Outmessage=Outmessage+"SERVER>>>Connection successful";
output.writeObject(Outmessage);
output.flush();
do ///process messages sent from client
try
Inmessage = (String) input.readObject();
System.out.println(Inmessage);
/* //while the connection is open each line
that is passed from the client to the server
is read in and is displayed*/
messageDetails.setMessage(Inmessage);
String CurrentMessage=messageDetails.getMessage();
//output.writeObject(CurrentMessage);
// output.flush();
passOnMessage.FloodMessage(CurrentMessage);
//sending out the message
catch(ClassNotFoundException classNotFoundException){}
}while (!Outmessage.equals("CLIENT>>>TERMINATE"));
/*this my attempt at broadcasting the message to all clients
my thinking was that you could create a array of objectoutputstreams
which in turn could be broadcasted(bit confussed here)*/
import java.io.*;
import java.net.*;
public class BroadCastMessage /// implements Runnable
private int count;
private String Inmessage="";
private ObjectOutputStream temp=null;
private ObjectOutputStream[] output = new ObjectOutputStream [12];
//temp level of array of objects
public BroadCastMessage()
count=0;
public synchronized void FloodMessage(String message) throws IOException
System.out.print(count);
for(int i=0;i<count+1;i++)
try
{ System.out.print(count);
output[count].writeObject(message);
output[count].flush();
catch(IOException ioException)
{ioException.printStackTrace();}
notifyAll();
public ObjectOutputStream getOutputObject(ObjectOutputStream out,Socket caller,int Ocount)
try
{ temp = new ObjectOutputStream(caller.getOutputStream());
AddObjectOutputStream(temp,Ocount);
////FloodMessage();
catch(IOException ioException)
{ioException.printStackTrace();}
return temp;
public void AddObjectOutputStream(ObjectOutputStream out,int Ocount)
{ ///add new object to array
count=Ocount;
output[count]=out;
System.out.print("\nthe number of output streams : "+count+"\n");
} -
Help with MIDlets - TCP client server program
Hi I am new to using MIDlets, and I wanted to create a simple TCP client server program.. I found a tutorial in J2me forums and I am able to send a single message from server(PC) to client(Phonemulator) and from client to server. But I want to send a stream of messages to the server. Here is my program and I am stuck in the last step wher i want to send lot of messages to server. Here is my program, Could any one of u tell me how to do it? Or where am i going wrong in thsi pgm?
Code:
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeExcepti on;
public class SocketMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display display;
private Form addressForm;
private Form connectForm;
private Form displayForm;
private TextField serverName;
private TextField serverPort;
private StringItem messageLabel;
private StringItem errorLabel;
private Command okCommand;
private Command exitCommand;
private Command backCommand;
protected void startApp() throws MIDletStateChangeException {
if (display == null) {
initialize();
display.setCurrent(addressForm);
protected void pauseApp() {
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
public void commandAction(Command cmd, Displayable d) {
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
display.setCurrent(connectForm);
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
notifyDestroyed();
public void run() {
InputStream is = null;
OutputStream os = null;
StreamConnection socket = null;
try {
String server = serverName.getString();
String port = serverPort.getString();
String name = "socket://" + server + ":" + port;
socket = (StreamConnection)Connector.open(name, Connector.READ_WRITE);
} catch (Exception ex) {
Alert alert = new Alert("Invalid Address",
"The supplied address is invalid\n" +
"Please correct it and try again.", null,
AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
try {
// Send a message to the server
String request = "Hello\n\n";
//StringBuffer b = new StringBuffer();
os = socket.openOutputStream();
//for (int i=0;i<10;i++)
os.write(request.getBytes());
os.close();
// Read the server's reply, up to a maximum
// of 128 bytes.
is = socket.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total<=5)
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0)
break;
total += count;
is.close();
String reply = new String(buf, 0, total);
messageLabel.setText(reply);
socket.close();
display.setCurrent(displayForm);
} catch (IOException ex) {
Alert alert = new Alert("I/O Error",
"An error occurred while communicating with the server.",
null, AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
} finally {
// Close open streams and the socket
try {
if (is != null) {
is.close();
is = null;
} catch (IOException ex1) {
try {
if (os != null) {
os.close();
os = null;
} catch (IOException ex1) {
try {
if (socket != null) {
socket.close();
socket = null;
} catch (IOException ex1) {
private void initialize() {
display = Display.getDisplay(this);
// Commands
exitCommand = new Command("Exit", Command.EXIT, 0);
okCommand = new Command("OK", Command.OK, 0);
backCommand = new Command("Back", Command.BACK, 0);
// The address form
addressForm = new Form("Socket Client");
serverName = new TextField("Server name:", "", 256, TextField.ANY);
serverPort = new TextField("Server port:", "", 8, TextField.NUMERIC);
addressForm.append(serverName);
addressForm.append(serverPort);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);
// The connect form
connectForm = new Form("Connecting");
messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);
// The display form
displayForm = new Form("Server Reply");
messageLabel = new StringItem(null, null);
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);Hello all,
I was wondering if someone found a solution to this..I would really appreciate it if u could post one...Thanks a lot..Cheerz
Maybe you are looking for
-
Crystal Report with text(csv) data file, can we set it as input parameter?
Hi, I am a new user of Crystal Reports 2008. I have created a report with charts in it. The input data comes from a csv text file. Can I set the name of this text file as an input parameter? as I need to generate 44 similar reports with different tex
-
How do you sync iTouch to iTunes if you don't own or have access to a computer?
For some time now, my iTouch 4 iOS 4.3.2 (or whatever the latest iOS Apple still provided for this particular device), 59.1 GB, with wi-fi, no cellular, has displayed a screen message indicating there is no room to complete download of song(s) or to
-
HT201442 My phone wont restore. It is showing error 3194. How do I fix this?
My battery went flat. I charged the phone (Iphone 5) up again and tried to open using my fingerprint. Got a message that I needed to enter the PIN because it was restarting. Entered the PIN - a number engraved on my mind for years - but it would not
-
I have just installed arch linux following this part of wiki https://wiki.archlinux.org/index.php/Dm - VM_on_LUKS (also for partitioning made with cgdisk). I havn't find any problem untill i have rebooted the machine. My pc can't find the bootloader
-
Macbook fan keeps running, won't sleep or hibernate
So here's the deal, my macbook (late 2008 aluminum) fan is always running loudly, from 4500-6000 rpm, and the temperature stays around 80ºF even if the computer is idling. I have to shut it off for the fan to turn off. When I close the lid, the scree