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
Similar Messages
-
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 -
HELP:USING CLIENT SERVER PROGRAM ON DIFF.MACHINES CONNECTED TO INTERNET?
BELOW IS THE JAVA CODE FOR CLIENT & SERVER PROGRAM (TCP) USING SOCKET.
I AM TRYING TO RUN CLIENT & SERVER PROGRAM ON 2 DIFFERENT MACHINES CONNECTED 2 INTERNET
(1 RUNS SERVER.java & OTHER CLIENT.java).
IS IT POSSIBLE WITH THE CODE WRITTEN BELOW?
// Server.Java
import java.net.*;
import java.io.*;
class Server {
public static void main(String[] args) {
boolean finished = false;
try{
ServerSocket listener = new ServerSocket(4444);
while(!finished)
{Socket to_client = listener.accept();
OutputStream out = to_client.getOutputStream();
PrintWriter pout = new PrintWriter(out, true);
pout.println("Hello! this is server talking to you.");
to_client.close();
listener.close();
}// end of try
catch(Exception ie) {
System.out.println(ie);
//Client.Java
import java.net.*;
import java.io.*;
class Client
public static void main(String[] args)
Socket client;
String host="serverpcname";//host is assigned name of the server
try
{InetAddress adressen = InetAddress.getByName(host);
client = new Socket(adressen,4444);
BufferedReader scanf = new BufferedReader(new
InputStreamReader(client.getInputStream()));
String someString = scanf.readLine();
System.out.println("From Server: "+someString);
client.close();
catch(Exception e)
System.out.println(e);
WHEN THE CODE IS EXECUTED(CLIENT.java ON 1 PC & SERVER.java on other) IT GIVES FOLLOWING EXCEPTIONS:
java.net.UnknownHostException: serverpcname: serverpcname
PLZ. GUIDE ME.
THANKS IN ADVANCE.For a server to be accessible on the inetrnet it needs to have an externally visible IP address. For example, an address which starts with 192.168.1 is for internal use only can only be used by other machines on the same internal network. The server's firewall needs to allow the port you are using access and the client has to be able to lookup up the IP address either using the hosts file or via a DNS service. None of these things have anything to do with Java programming, so if you have any more questions I sugegst you try googling them or ask a forum which relates to these issues.
The connection time out is due to the fact that there is no way to contact an inetrnal address over the inetrnet. The host unknwown means you haven't configured your PC to lookup that address. i.e. the host is unknown. -
About the communication issues in the client-server program
About the communication issues in the client-server program
Hi, I have some questions about the communication issues in a java project, which is basically the client and server architecture. In brief, the client, written in java, can be deployed anywhere, and in the following part, assume it is in the LAN (Local Area Network) which is connnected to the internet through the firewall and/or proxy, and the server, written in
java too, simply provides the listening service on a port in a remote machine. And assume the server is connected to the internet directly so that the scenario can be simple to focus on the core questions.
My questions are as follows:
1 About the relationship between the communication port and protocol
Generally, protocols at the application level like HTTP, FTP have their own default port, e.g., HTTP is corresponding to 80,
FTP is to 25. But it is NOT necessary for the web server to provide the HTTP listening service at port 80, right? E.g, Tomcat provides the HTTP listening service at 8080. So it means the default relationship between the application protocl and their port is some routine, which is not necessary to follow, right?
2 Assume a LAN connected to the internet through a proxy, which only allows HTTP protocol, then questions are:
2.1 Does the proxy recognize the HTTP request from the client by the port number (carried in the request string)? For example, when the server provides the HTTP listening service at 80, then the request from the client will include the port number 80, then the proxy will parse such info and decide if or not the request can be out.
2.2 Does the proxy recognize the HTTP request from the client by protocol (carried in the request string)? For example, the protocol used in the communicatin should be included in the request, then the proxy can parse it to make the decision.
3 In java programm, if using the HTTP protcol, then on the client: the corresponding API is java.net.URLConnection, right?
If using the TCP protocol directly, then on the client:the corresponding API is java.net.Socket, right? In both cases, the server side use the same API, java.net.ServerSocket?
Is it correct to say that the communication by Socket is faster than URLConnection?
4 Take MSN messenger for example, which protocol does it use? Since proxy configure is only the possible option, so I guess generally the TCP protocol is used directly so that the better perfomrance can be achieved, right?
5 Given 3 computers within the same LAN, can the client, proxy, server environment above be correctly simulated? If so, can
you recommend me some typical proxy program so that I can install it to configure such an enviroment to perform some test?
6 I guess there should be some software to find out which port number a given program/process is going through to connect to
the remote machine, and which port number a given program/process is listening on? Also, what protocl is used in the given
communication.
7 Finally, regarding each of the above questions, it will be highly appreciated that if you can recommed some references,
tutorials, books etc. In summary, what I care about is how to enable the java client behind the proxy and firewall to
communicate with the remote server without problems, so if you know some good tutorials plz let me know and thx in advance!
Finally, thanks for your attention so such long questions =).FTP is to 25. But it is NOT necessary for the web
server to provide the HTTP listening service at port
80, right? E.g, Tomcat provides the HTTP listening
service at 8080. So it means the default relationship
between the application protocl and their port is
some routine, which is not necessary to follow,
right?Not sure what you're saying here.
There must be a server listening on some port. The client must know what port that is. If you open the connection using the Socket class, you'll explicitly specify the port. If you use some higher level class like URLConnection or something in the commons Net package, there's probably a default port that will be used if you don't explicitly specify another.
There's no way for the client to know that the HTTP request will go to port 80 instead of port 8080. If you think the the client contacts the server without explicitly naming a port, and then asks the server "get me your HTTP server", and the port is determined from that, you're mistaken.
Not sure if you're thinking that, but it sounded like you might be.
2 Assume a LAN connected to the internet through
a proxy, which only allows HTTP protocol, then
questions are:
2.1 Does the proxy recognize the HTTP request
from the client by the port number (carried in the
request string)? For example, when the server
provides the HTTP listening service at 80, then the
request from the client will include the port number
80, then the proxy will parse such info and decide if
or not the request can be out. I'm not sure, but I think most proxies and firewalls are configured by ports. I thought I'd heard of more sophisticated, higher-level ones that could understand the content to some degree, but I don't know anything about those.
3 In java programm, if using the HTTP protcol,
then on the client: the corresponding API is
java.net.URLConnection, right?That's one way.
You might want to look into this:
http://jakarta.apache.org/commons/httpclient/
If using the TCP protocol directly, then on the
client:the corresponding API is java.net.Socket,
right? In both cases, the server side use the same
API, java.net.ServerSocket? A Java client will user Socket, and a Java server will use ServerSocket and Socket.
Is it correct to say that the communication by Socket
is faster than URLConnection?Probably not. -
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! -
Design Pattern for multithreaded client server program
I asked this question in another post, but with other stuff, so I'll distill this one.
I am creating a multi-threaded client server program (just for learning - a chat program at this point). I built the server and client in swing, and I'm wondering what the best design pattern is for this setup. Right now all the swing stuff is in the MyServer class. In that class I have a loop accepting client connections to the serverSocket and creating a new MyServerThread (threaded client connection).
The problem is that all the work of creating input streams, interacting with the server, all that stuff is done in the MyServerThread class, but I want that text to be written up to the Swing objects - which is in the MyServer class. So right now in the MyServerThread class I pass the MyServer object into it, but I'm not sure if that is really the most robust thing to do. Does anybody have any suggestions as to how this should be done. If somebody has an article they'd like to point to I'll check it out too. But if it's just the run-of-the-mill multithreaded client-server article, I've read alot and most don't specifically address my question.Thanks for the reply Kaj, and I think I'll keep my design for now, since it's just quick and dirty. I've read the MVC concept a while ago and I'll revisit it again when I get more serious. But I have a question, why should I be using a callback interface, why an interface at all? And then make MyServer implement that interface...why not just pass MyServer to the thread object? Or is there something down the line that I did not forsee?
-
Muti-channel read/write through FP data socket posible?
Hello,
I'm trying to talk to cFP-1808 module from desktop PC real-time host over Ethernet. I did not find any Fieldpoint driver for desktop RT so I'm forced to use data sockets to communicate with cFP-1808. It seems that one can only read or write to one FP data channel per socket. With typical latency of tens of milliseconds per such read/write and couple of hundreds channels present, I'm looking at SECONDS per cycle time, which is really slow.
Is there any workaround for this problem?You can also read and write to channels in LabVIEW. First you have to configure your 1808 in MAX and save the IAK file. You then load the IAK file in LabVIEW by selecting browse in the FieldPoint IO Point In (constant or control).
In the FieldPoint Device Selection Dialog Windows select the View Configurations Tab.
In this tab navigate to your IAK file and name it in the text box next to where the full file path is displayed.
In the Browse FieldPoint Tab of the same window you should now be able to see all of your FieldPoint modules and channels.
Message Edited by BLAQmx on 03-06-2008 01:12 PM
Mark
LabVIEW R&D -
File transfer using non-blocking sockets - data mysteriously vanish
Hello,
I need to pass some big amount of data using sockets. I my appliaction I have noticed that sometimes I didn't get all bytes. To check it out I wrote simple client + server to figure out what is happening. So:
- I have a sender and receiver application
- I'm trying to transfer 5MB text file.
- On receiver side, output file is never larget than 3MB
- If I put some timeout on sender side (1ms timeout between write operations) everything works fine.
Could someone tell me what I do wrong? Why data disappears and when? The same file transfered using old sockets goes always fine...
Thanks in advance!
Here is complete source for receiver and sender:
RECEIVER:
import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class ReceiverA {
* @param args
public static void main(String[] args) {
String outputFile = "c:\\outputA.txt", host = "127.0.0.1";
int port = 8001, bufferSize = 10240;
try {
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
Selector selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(host, port));
server.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server started");
while(true)
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if (key.isAcceptable()) {
SocketChannel client = server.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
continue;
SocketChannel channel = (SocketChannel) key.channel();
int counter = 1;
if ( key.isReadable() ) {
FileOutputStream os = new FileOutputStream(outputFile);
int res;
do
buffer.clear();
res = channel.read(buffer);
counter += res;
System.out.println(res);
buffer.flip();
os.write(buffer.array(), 0, buffer.limit());
while( res >= 0 );
channel.close();
os.close();
System.out.println("Receiver: " + counter);
return;
} catch (Exception e) {
e.printStackTrace();
}SENDER:
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class SenderA {
public static void main(String[] args) {
String inputFile = "c:\\inputA.txt" , host = "127.0.0.1";
int port = 8001, bufferSize = 10240;
try {
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
byte[] byteArr = new byte[buffer.capacity()];
Selector selector = Selector.open();
SocketChannel connectionClient = SocketChannel.open();
connectionClient.configureBlocking(false);
connectionClient.connect(new InetSocketAddress(host, port));
connectionClient.register(selector, SelectionKey.OP_CONNECT);
while(true) {
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys()
.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
SocketChannel client = (SocketChannel) key.channel();
if (key.isConnectable()) {
if (client.isConnectionPending()) {
System.out.println("Trying to finish connection");
try {
client.finishConnect();
} catch (IOException e) {
e.printStackTrace();
client.register(selector, SelectionKey.OP_WRITE);
continue;
if(key.isWritable()) {
FileInputStream is = new FileInputStream(inputFile);
int res;
int counter = 0;
do
buffer.clear();
res = is.read(byteArr, 0, byteArr.length);
System.out.println(res);
if ( res == -1 ) break;
counter += res;
buffer.put(byteArr, 0, Math.min(res, buffer.limit()));
buffer.flip();
client.write(buffer);
* When I remove comment file transfer goes OK!
//Thread.sleep(1);
while( res != -1 );
client.close();
is.close();
System.out.println("Receiver: " + counter);
return;
catch(Exception e) {
e.printStackTrace();
}There are at least two problems here.
A. In the receiver you should test for -1 from the read() immediately, rather than continue with the loop and try to write -1 bytes to the file.
B. In the sender you are ignoring the return value of client.write(), which can be anything from 0 to the buffer length. If you get 0 you should wait for another OP_WRITE to trigger; if you get a 'short write' you need to retry it until you've got nothing left to write from the current buffer, before you read any more data. This is where the data is vanishing. -
Cannot send and read objects through sockets
I have these 4 classes to send objects through sockets. Message and Respond classes are just for
trials. I use their objects to send ıver the network. I do not get any compile time error or runtime error but
the code just does not send the objects. I used object input and output streams to send and read objects
in server (SOTServer) and in the client (SOTC) classes. When I execevute the server and client I can see
that the clients can connect to the server but they cannot send any objects allthough I wrote them inside the main method of client class. This code stops in the run() method but I could not find out why it
does do that. Run the program by creating 4 four classes.
Message.java
Respond.java
SOTC.java
SOTServer.java
Then execute server and then one or more clients to see what is going on.
Any ideas will be appreciated
thanks.
ASAP pls
//***********************************Message class**********************
import java.io.Serializable;
public class Message implements Serializable
private String chat;
private int client;
public Message(String s,int c)
client=c;
chat=s;
public Message()
client=0;
chat="aaaaa";
public int getClient()
return client;
public String getChat()
return chat;
//*******************************respond class*****************************
import java.io.Serializable;
public class Respond implements Serializable
private int toClient;
private String s;
public Respond()
public Respond(String s)
this.s=s;
public int gettoClient()
return toClient;
public String getMessage()
return s;
//***********************************SOTServer*********************
import java.io.*;
import java.net.*;
import java.util.Vector;
//private class
class ClientWorker extends Thread
private Socket client;
private ObjectInputStream objectinputstream;
private ObjectOutputStream objectoutputstream;
private SOTServer server;
ClientWorker(Socket socket, SOTServer ser)
client = socket;
server = ser;
System.out.println ("new client connected");
try
objectinputstream=new ObjectInputStream(client.getInputStream());
objectoutputstream=new ObjectOutputStream(client.getOutputStream());
catch(Exception e){}
public void sendToClient(Respond s)
try
objectoutputstream.writeObject(s);
objectoutputstream.flush();
catch(IOException e)
e.printStackTrace();
public void run()
do
Message fromClient;
try
fromClient =(Message) objectinputstream.readObject();
System.out.println (fromClient.getChat());
Respond r=new Respond();
server.sendMessageToAllClients(r);
System.out.println ("send all completed");
catch(ClassNotFoundException e){e.printStackTrace();}
catch(IOException ioexception1)
ioexception1.printStackTrace();
break;
Respond k=new Respond();
sendToClient(k);
}while(true);
public class SOTServer
ServerSocket server;
Vector clients;
public static void main(String args[]) throws IOException
SOTServer sotserver = new SOTServer();
sotserver.listenSocket();
SOTServer()
clients = new Vector();
System.out.println ("Server created");
public void sendMessageToAllClients(Respond str)
System.out.println ("sendToallclient");
ClientWorker client;
for (int i = 0; i < clients.size(); i++)
client = (ClientWorker) (clients.elementAt(i));
client.sendToClient(str);
public void listenSocket()
try
System.out.println ("listening socket");
server = new ServerSocket(4444, 6);
catch(IOException ioexception)
ioexception.printStackTrace();
do
try
ClientWorker clientworker=new ClientWorker(server.accept(), this);
clients.add(clientworker);
clientworker.start();
catch(IOException ioexception1)
ioexception1.printStackTrace();
while(true);
protected void finalize()
try
server.close();
catch(IOException ioexception)
ioexception.printStackTrace();
//*************************SOTC***(client class)*********************
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
class SOTC implements Runnable
private Socket socket;
private ObjectOutputStream output;
private ObjectInputStream input;
public void start()
try
socket= new Socket("127.0.0.1",4444);
input= new ObjectInputStream(socket.getInputStream());
output= new ObjectOutputStream(socket.getOutputStream());
catch(IOException e){e.printStackTrace();}
Thread outputThread= new Thread(this);
outputThread.start();
public void run()
try
do
Message m=new Message("sadfsa",0);
output.writeObject(m);
Respond fromServer=null;
fromServer=(Respond)input.readObject();
}while(true);
catch(NullPointerException e){run();}
catch(Exception e){e.printStackTrace();}
public SOTC()
start();
public void sendMessage(Message re)
try
Message k=new Message("sdasd",0);
output.writeObject(k);
output.flush();
catch(Exception ioexception)
ioexception.printStackTrace();
System.exit(-1);
public static void main(String args[])
SOTC sotclient = new SOTC();
try
System.out.println("client obje sonrasi main");
Message re=new Message("client ım ben mesaj bu da iste",0);
sotclient.sendMessage(re);
System.out.println ("client gonderdi mesaji");
catch(Exception e) {e.printStackTrace();}ObjectStreams send a few bytes at construct time. The OutputStream writes a header and the InputStram reads them. The InputStream constrcutor will not return until oit reads that header. Your code is probably hanging in the InputStream constrcutor. (try and verify that by getting a thread dump)
If that is your problem, tolution is easy, construct the OutputStreams first. -
How to create files with read/write privileges for everyone?
I have two iMacs 7,1 (one with Snow Leopard and the other with Mountain Lion) in a local area wireless network.
I have shared the "documents" folder in the Snow Leopard iMac in order to have files available to the other iMac. The folder has read/write privileges for everyone.
When I create a new file in the shared "Documents" folder (for example a new Open office document, or a Keynote presentation) this file is by default "read/write" for the Administrator but only "read" for all the other users, so when I try to open it from the other iMac, I am informed that the file is "read only".
I can obviously change the privileges of the file in the information window, but I have to do on a file per file basis and this takes too long.
Is it possible to change settings in order to create files which are always "read/write" for everyone?
And, secondly, since I have several existing files whose privileges I should manually change one by one, is it possible to make global changes of their privileges?
Thanks in advance
Best regardscouple of different changes - 1st, if you want to share folders, doing your whole documents folder is not the best way. Since both your computers can handle AidDrop, that's what I would recommend - http://osxdaily.com/2011/11/14/how-to-use-airdrop-in-mac-os-x/ - as it create an instant Ad-Hoc network between the two computers and then let's it done.
A second possibility that may not be what you're looking for, is to use google drive or some similay cloud sharing app to sync the documents back and forth. both of these solutions will transfer the files well, but the airdrop may be simplest -
Deliver file with read/write properties on target side using receiver file
Hi All,
Our file-to-file scenario works fine. By default, PI creates file on target directory with the 644 permissions. Files coming inbound from PI are not read/writable to the group. Currently the files from PI are coming across with 644 permissions and they should be 664 or 660. Is there a way to generate read/write files on targer side using SAP PI??
Thanks in advance,
- Riya PatilHello,
Try using Run-Operating system command after processing parameter with the below mentioned command:
chmod 0755 /usr/sap/tmp/test/*
where: /usr/sap/tmp/test/ is the directory path location.
Br,
Rahul -
File Sharing (Read & Write) with a Network User - "Network User" Not Listed
My boyfriend and I both have Macs, running 10.6.3. Both Macs are connected to the internet via Apple Wireless Express. I have a MacBook Pro, and my boyfriend has an iMac with a big fancy screen, so I like to use for my own work when I'm at home and he isn't - it's just easier and more comfortable to use than a laptop.
I would like to find a way to use his computer to access a shared folder on my laptop with read & write access (so that I can modify the files on my laptop while using his computer). I have gotten to the point where I have a folder on my laptop with the files I want shared with his computer, and can access this folder from his computer. However, doing it this way (accessing my files on my laptop from his computer) only allows read-only access. I would like to be able to edit the files that are on my laptop using his computer, so I think I would need read and write access.
It seems the easiest way to do this would be to add a user (the boyfriend) on my laptop and give him read/write access to this specific folder that is located on my laptop. I found instructions on how to do this, and it says that I need to add a "network user". These instructions seem to indicate that when I add a user, there should be options for accounts on my laptop, my personal address book, a new account on my laptop, and network users. I see the first 3 options...but no option to add a network user.
Why is that? How would I make it so that from my laptop, I can add a network user...specifically my boyfriend's computer, who also uses the same internet network that I use?
Thank you so much for any help!Also found this behavior:
While logged into the Mac Pro as MPUser1, I connect to the MacBook Pro file sharing as MBPUser1.
Then I "disconnect".
Then I log out of the Mac Pro MPUser1, and login as MPUser2.
The connection to MBP as MBPUser1 is still active!
This means that MPUser2 can access whatever MBPUser1 can access WITHOUT knowing MBPUser1's login password !
This seems WRONG! Anybody else seen this? -
How do a make a file permanent read/write?
I have a file shared on the server and when someone accesses it it changes the ownership to them and makes the file read-only to everyone else (that person uses XP). I want to make it permanent read/write. What is the command to do this in terminal?
If the file is in a share point managed by the server you will need to use 'Server Admin.app' to set up the ACL's.
-
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
Maybe you are looking for
-
How to reinstall Recovery HD after full Time Machine recover?
I had to recover my primary Macinstoh HD to a new disk from Time Machine, but somehow I now lost my Recover HD on the Macintosh HD. To do the initial recover I had to install Mac OS X Lion on a 2nd internal Hard Drive, but now I want to use Time Mac
-
XSLT Transformation and GUI_UPLOAD
Can I use the GUI_UPLOAD to upload a XML in ABAP? The problem is that I have to use an internal table for the upload but for the transformation I need a string, and both together don't work.
-
XSLProcessor support of xsl:output method="text"?
I'm having trouble getting my processor to format the output as a big string. Actually, the output is html, but because of some browser bugs I want to avoid linebreaks between tags. Specifically table cell tags <td> and the content of the cell. Right
-
Bluetooth antenna died - third device with identical failure
I have: Blackberry Pearl 8220 OS version 4.6.0.180 TMobile service 57577421 bytes free space no applications I got my first Blackberry Pearl 8220 about a year ago. It died, and I was given a new one. (I bought the extended warranty.) Then the Bluet
-
After Installing Bitdefender 2011 Firefox is very slow and worse when multiple tabs are open
Firefox performs very poorly after I installed Bitdefender 2011. There was no such problem with Bitdefender 2009. When multiple tabs are open, switching between them is not possible until tab contents are completed.