ObjectOutputStream/ObjectInputStream/Socket Problem
I make request on a server with socket connection.
I want to use one socket open connection.
So, I don't close the socket.
This is like that :
public void serverConnection()
try
DataOutputStream out = new DataOutputStream(s.getOutputStream());
ObjectOutputStream objectOutStream = new ObjectOutputStream(out);
objectOutStream.writeObject(configConnection);
DataInputStream in = new DataInputStream(s.getInputStream());
ObjectInputStream objectInStream = new ObjectInputStream(in);
arrayBlocks = (BFTransactionBlock[]) objectInStream.readObject();
} catch (Exception e)
valid = false;
System.out.println("Error " + e);
When I use this funtion more then one time with the same socket, the prorgam wait an the instruction :
ObjectInputStream objectInStream = new ObjectInputStream(in);
I use objectInStream.close() ...
But it create an other problem : i lost the socket connection.
What's the solution ?
You don't need a new input stream for the same socket. You just need to read the data off of the original socket.
DataInputStream in = new DataInputStream(s.getInputStream());
ObjectInputStream objectInStream = new ObjectInputStream(in);The above code is fine. You need to loop through the code below until you are done with the socket. Then you close the socket. If you close the stream, you will close the underlying socket.
arrayBlocks = (BFTransactionBlock[]) objectInStream.readObject();
Similar Messages
-
ObjectInputStream - ObjectOutputStream, socket problem
Hello,
I'm tring to send and receive some object between a client and a server application.
When the client application send an object the server is stock.
This is a part of the server code:
try
inObj = new ObjectInputStream(client.getInputStream()); /// here the server program is stock
mes1 = (Message) inObj.readObject();
System.out.println(mes1);
out.println("end");
catch (ClassNotFoundException e)
e.printStackTrace();
catch(IOException e)
e.printStackTrace();
The client code:
try
in=new BufferedReader(new InputStreamReader(soclu.getInputStream()));
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(soclu.getOutputStream())),true);
outObj = new ObjectOutputStream(soclu.getOutputStream());
out.print("Info");
// out.flush();
outObj.writeObject(m1);
outObj.flush();
raspuns = in.readLine();
System.out.println(raspuns);
System.out.println("Closing the communication!");
out.print("end");
out.close();
in.close();
outObj.close();
soclu.close();
catch(IOException e)
System.out.println("Problems Tx/Rx");
e.printStackTrace();
The class Message implements Serializable
if there is somebody hwo cold help me I appreciate that.
Thnak you,
aclaudia1You should not be opening both a PrintWriter and an ObjectOutputStream on the same socket. You should use a single stream to do all the output on the socket.
-
Hi ,
I written a server class that simply writes the numbers and the client simply reads those numbers and prints them. When I run the both client and server on tha same machine there is no data loss found. But when I run the server on different machine than client I found heavy dataloss.(while theserver written numbers from 1-9000 the client is able read only 6000 plus). The data loss is increased when the data read from the server socket created by the VB application. Here with i am pasting the code snippet for the Server and the Client java files . Please help me in solving this problem.
Client.java
import java.net.*;
import java.io.*;
public class Client
static Socket client = null;
ObjectInputStream is = null;
public Client() throws Exception
client = new Socket("rajsekhar",3333);
is = new ObjectInputStream (client.getInputStream());
while(true){
Integer in = (Integer)is.readObject();
System.out.println(in.toString());
public static void main(String[] args) throws Exception
new Client();
Server.java
import java.net.*;
import java.io.*;
public class Server
public static void main(String[] args) throws Exception
ServerSocket server = null;
server = new ServerSocket(3333);
Socket s = server.accept();
ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
int i =1;
while(true)
os.writeObject(new Integer(i));
System.out.println(i);
i++;
please help me .
thanks in advance,
Sridhar Reddy .RThis has nothing to do with JSSE; please post in a more appropriate forum.
-
ObjectInputStream JXTA problem
I'm trying to read an object from an ObjectInputStream (created from a JxtaSocket) like this:
Object obj = ois.readObject();
If the object is a String Object everything works just fine!
If the object for example is an ImageIcon, Integer or a custom object that is serializable I get a:
java.io.StreamCorruptedException
at java.io.ObjectInputStream.readObject()
what is wrong ?and this is the client related stuff ,
the problem accures in the out.writeObject(t) ,
i have an SocketException , and it says :
"socket write error ".
what can it be ?
public void init(){
t=new Merkava();//temp , for checking
System.out.println("Client: initializing");
try{
addr=InetAddress.getByName("localhost");
}catch(IOException e){System.out.println("Client: unable to recieve address");}
try{
s=new Socket(addr,Server.PORT);
}catch(IOException e){System.out.println("Client: unable to create socket");}
try{
out=new ObjectOutputStream((s.getOutputStream()));
}catch(IOException e){System.out.println("Client: unable to create outputstream");}
try{
recv=new RecieveData(s);
}catch(IOException e){System.out.println("Client: unable to create inputstream");}
System.out.println("Client: initializing finished");
public void start(){
try{
out.writeObject(t); //registers the tank in the server
// System.out.println("Client: registerd tank");
//THE PROBLEM ACCURES HERE!!!!!!
}catch(IOException e){
System.out.println("Client: unable to send data");}
if(runner==null){
runner=new Thread(this);
runner.start();
} -
Can I send a my defined object to another computer by the following code :
Socket socket=new ( xxx.......
try {
ObjectOutputStream objectOutputStream =new ObjectOutputStream (socket.getOutputStream);
objectOutputStream .writeObject(myObject);
} catch(Exception e){
e.printStackTrace();
There is "java.io.NotSerializableException" occur , how can I correct this problem ?Hello!
The object that you are sending must implement Serializable, i.e.
class MyObject implements Serializable{ -
Data socket problems with LVRT 8.2
I am in the process of migrating to LV 8.2 from LV7.1.1. My system has 18 RT targets which send data to a Host PC through data socket (DS). The Host PC runs LV on Windows XP Pro. With LV7.1.1 on both host and RT targets DS works perfectly. The RT targets update the host every 500 ms.
I've taken a three-step process in the migration. First tests were done with the host migrated to LV8.2 while keeping the RTs at LV7.1.1. Result: the system worked perfect. Then I changed one RT to 8.2 keeping the rest the rest at LV7.1.1. Result: DS timed out before all the data could be sent to Host. Finally, all RTs were migrated to LVRT 8.2. Result: Only about 5 out of the 18 RTs report to the Host before DS times out. However, if only one RT target is used, i.e., the other 17 RTs are diasbled, communication is very fast. Is there a special setting that I need to make? Btw, the roughly 5 RTs that report vary randomly from test to test, i.e., there is no bias towards any particular RTs.
I am using the same source code developed under LV7.1.1, so the only changes made are the ones that take place when one opens LV7.1.1 code in LV8.2. Some VIs get converted in the process.
Any ideas?
Chatonda Mtika
Algis Corp
Vancouver, CanadaBen,
I must say I am very surprised by Nadim's email. His point, which I must say I don't agree with, was made quite clear to me yesterday during a conference call between my team and the NI team comprising Chris, Nadim, and Avinash. So I don't know what purpose this morning's email is supposed to serve. Be that as it may, I think NI has gotten it wrong here. I do not think it should be one or the other. The discussion forum is a much wider forum comprised of people with varying experiences - not just NI employees. That is precisely why I posted my problem to the forum: to tap into the vast experiences of the discussants. But when I did not get any responses after I had posted answers to Nadim's questions, I decided to make a formal service request to NI, all perfectly legal. So I was really surprised when I was being blamed for tying up NI resources on one problem. I believe the resource allocation issue should be NI's to solve, not mine. I have no way of knowing that NI had formally assigned somebody to my problem. What if nobody from NI responds, am I allowed to make a service request to NI? My feeling is that NI's logic is flawed here, assuming Nadim's views are NI's views.
Thanks,
Chatonda Mtika
Algis Corporation
Vancouver, Canada -
Serversock/socket problem pls Help
Hi all,
I have a serversocket that accepts client's connections, reads from this stream, processes the data and sends back response to the client. This works fine for a standard scenario.
The problem occurs if for some reason the client looses connection after writing to the serversocket. The server behaves as if nothing happens and sends back the response. I want the server to be able to detection any connection loss and report back. My code snippet is shown below
ServerSocket server;
Socket conn;
BufferedReader input;
PrintWriter out;
try{
server= new ServerSocket(4550,10);
conn=server.accept();
input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String data=input.readLine();
process data .....
out = new PrintWriter(conn.getOutputStream(), true);
out.println(processed_data);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
input.close();
out.close();
conn.close();
}catch(Exception uncaught){}
If during process data, the client looses connection, the program behaves as if the connection still exist. Any suggesion would be highly appreciated
Regards
Timerr, yeah, i got that bit....
and there is nothing, nothing at all in java, C, C++, any and i mean ANY TCP/IP programming that can tell if the client has been unplugged without trying to send something to it
you can use a keepAlive in Socket to automatically occasionally send a dummy packet (for which it expects a response)
but apart from that the Socket cannot know it is not connected unless it recieves indication from the client (the end that is closed first sends a FIN packet and the other end replies with ACK FIN)
a pair of Sockets connectd through a network does not get a permanent physical connection, they give the impression of such by exchanging packets with sequence numbers and ack numbers coresponding to the last packet recived.
if neither Socket has nothing to send, nothing is sent and it is assumed that the connection is still valid, so isConnected() will return true unless it actually knows that the client has closed the connection or an Exception occured when it tried to send something
isConnected() does not test the connection, just reports true if it has been connected and there has not been an IOException or either end has closed
maybe you could explain why you need to avoid sending the response if the client has been unplugged? -
Create OPC I/O server and front panel data socket problem
Hi all!
I installed the NI OPC server. When I try to create a new server I/O in a LabVIEW project I don't see the "OPC client" possibility.
Is something software missing?
Other question: I tryed to connect to OPC server using front panel data socket but my problem is same. When I click the numeric control and I go to the "data operation" menu there is no possibility to make data socket connection.
I don't know what is the problem.
I attached two pictures about my problem.
Solved!
Go to Solution.Dear vajasgeri1,
do you have LabVIEW DSC module installed? Without it you will not have the OPC client funtionality.
And to configure DataSocket binding you need to go to the Data Binding tab in the Properties of a control.
BR,
Mateusz Stokłosa
Applications Engineer
National Instruments -
Socket Problem, Problem about printing the response from server
Or even I am not sure if there is a response from server. My code is like that
//Connection between, httpProxy and target adress
Socket clientSocket= new Socket("some host", 80);
DataOutputStream outToServer= new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//The first way
//outToServer.writeBytes("GET http://www.somehost.com/ HTTP/1.1"+ '\n');
//System.out.println("FROM SERVER: "+inFromServer.readLine());
//The second way
PrintWriter out_writer = new PrintWriter(outToServer, false);
out_writer.println("GET http://www.somehost.com/ HTTP/1.1");
out_writer.println("Host: localhost:80");
out_writer.println("Connection: Close");
out_writer.println();
//The second way cont.
String s = null;
while ((s = inFromServer.readLine()) != null)
System.out.println(s);
inFromServer.close();There are the two ways that I tried, and both of them didn't work. Why they are not working ? How can I solve it ?problem is solved, the reason it doesn't work is i didn't write the parts correctly. I mean it should be exactly the same packetIf you mean that the entire request must be sent in a single IP packet, this isn't true.
and host name must also be exactly sent to server.Of course.
They must be like in the wireshark.No. The actual data you send must be the same, but the server has no way of telling about what the IP packet looks like or how many there were.
One of your problems is that newlines in HTTP are defined as \r\n. In one case you're just using \n and in the other case you're using whatever the platform line terminator is. Neither is correct. -
Hi to All ,
I am facing problem regarding the Datagram Socket Programming .
I wana to make a java program that is using the datagram socket. I wana to retrive the IP Address of all the machines that are connected in a local network by using the datagram Socket !!!!!!!!!!!!!!
As i am new in java Socket Programming , Can any body help me How am i sends a Broadcast Packet to all the machines that are connected in a local network , so that i retrieve the IP Address of all the machines that are presented in a local network
Please give the SolutionYou can't use any Java to find all the machines on your network (whatever that means). You will need to shell out and parse the output from the shell.
If you want to simply use datagram sockets to send UDP broadcasts, the Javadoc covers it in some detail.
However, UDP is called a "send and pray" protocol - you send the message and pray that the client receives it. Also, there is no acknowledgement from the client when the message is received. So, in a nutshell, you cannot use multicasts to find clients.
You need to use some other protocols in the TCP/IP stack for finding machines on the network - and Java does not have any pre-built support for these. -
File transfer via socket problem (with source code)
I have a problem with this simple client/server filetransfer program. When I run it, only half the file is transfered via the net? Can someone point out to me why this is happening?
Client:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
// IPadressen til server
String host = "127.0.0.1";
int port = 4545;
//Lager streams
BufferedInputStream fileIn = null;
BufferedOutputStream out = null;
// Henter filen vi vil sende over sockets
File file = new File("c:\\temp\\fileiwanttosend.jpg");
// Sjekker om filen fins
if (!file.exists()) {
System.out.println("File doesn't exist");
System.exit(0);
try{
// Lager ny InputStream
fileIn = new BufferedInputStream(new FileInputStream(file));
}catch(IOException eee) {System.out.println("Problem, kunne ikke lage fil"); }
try{
// Lager InetAddress
InetAddress adressen = InetAddress.getByName(host);
try{
System.out.println("- Lager Socket..........");
// �pner socket
Socket s = new Socket(adressen, port);
System.out.println("- Socket klar.........");
// Setter outputstream til socket
out = new BufferedOutputStream(s.getOutputStream());
// Leser buffer inn i tabell
byte[] buffer = new byte[1024];
int numRead;
while( (numRead = fileIn.read(buffer)) >= 0) {
// Skriver bytes til OutputStream fra 0 til totalt antall bytes
System.out.println("Copies "+fileIn.read(buffer)+" bytes");
out.write(buffer, 0, numRead);
// Flush - sender fil
out.flush();
// Lukker OutputStream
out.close();
// Lukker InputStrean
fileIn.close();
// Lukker Socket
s.close();
System.out.println("File is sent to: "+host);
catch (IOException e) {
}catch(UnknownHostException e) {
System.err.println(e);
Server:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) {
// Portnummer m� v�re det samme p� b�de klient og server
int port = 4545;
try{
// Lager en ServerSocket
ServerSocket server = new ServerSocket(port);
// Lager to socketforbindelser
Socket forbindelse1 = null;
Socket forbindelse2 = null;
while (true) {
try{
forbindelse1 = server.accept();
System.out.println("Server accepts");
BufferedInputStream inn = new BufferedInputStream(forbindelse1.getInputStream());
BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:\\temp\\file.jpg")));
byte[] buff = new byte[1024];
int readMe;
while( (readMe = inn.read(buff)) >= 0) {
// Skriver filen til disken ut fra input stream
ut.write(buff, 0, readMe);
// Lukker ServerSocket
forbindelse1.close();
// Lukker InputStream
inn.close();
// flush - sender data ut p� nettet
ut.flush();
// Lukker OutputStream
ut.close();
System.out.println("File received");
}catch(IOException e) {System.out.println("En feil har skjedd: " + e.getMessage());}
finally {
try {
if (forbindelse1 != null) forbindelse1.close();
}catch(IOException e) {}
}catch(IOException e) {
System.err.println(e);
}Hi!!
The problem is at this line:
System.out.println("Copies "+fileIn.read(buffer)+" bytes");
Just comment out this line of code and see the difference. This line of code causes another "read" statement to be executed, but you are writing only the data read from the first read statement which causes approximately half the file to be send to the server. -
Reading data from socket problem
Hello;
I have implemented a multiplayer game with server java and client flash. I have a socket connection and I get(wait) an encripted data from server. However sometimes I can't get data from server. I know that server is sending the data but I can't see the data on the socket.
Sometimes I cannot get the data in one chunk but I have solved that problem(I hope).. Here is my code:
private function onSocketData(event:ProgressEvent = null) {
try {
var input:String = "";
var byteArray = new ByteArray();
socket.readBytes(byteArray, 0, socket.bytesAvailable);
input+= byteArray.toString();
queueOrg.addToMsgQueue(input);
} catch (error:Error) {
trace("SocketConnector -> onSocketData : "+error);
Thanks...And don't use ready() or available as a test for end of stream like that. That's not what it's for. (What is is for is a moot question.) Using it like that is a recipe for losing data.
-
MySQL socket problems after system update
I have been using my new Mac Mini Snow Leopard server as Squeezebox Server for over a month wihtout problems. After a system update this weekend I started to get MySQL socket errors after reboot.
Started; log sequence number 0 43655
091213 17:10:04 [ERROR] Can't start server : Bind on unix socket: Invalid argument
091213 17:10:04 [ERROR] Do you already have another mysqld server running on socket: /Users/admin/Library/Caches/Squeezebox/squeezebox-mysql.sock ?
091213 17:10:04 [ERROR] Aborting
Although I have posted this issue to the Squeezebox forum (http://forums.slimdevices.com/showthread.php?t=72510) where it primarily belongs to I wanted to hear if anyone maybe had an idea what recent changes in Apple updates could cause this? Maybe someone else has similar MySQL problems with other installations? I am a bit desperate by now so any idea or hint is appreciated.Here was my solution/workaround for this issue to the rest of us poor fellas that have too fight around with Squeezebox server from time to time:
I setup SBS to use the the standard MySQL installation on Mac OS X SL Server since I could get it to run without problems from Server Admin. Here are the instruction from the SBS Wiki:
http://wiki.slimdevices.com/index.php/ExistingMySQLInstance
However, I had to deviate a bit from that in order to make it work since it seems a bit outdated.
First deviation was necessary for the MySQL access privileges. Notice the extra grant to slimserver@localhost. Don't ask me why but this worked. I do also not know whether both grants would be necessary because I haven't tried it. Feel free to improve it:
# mysql -u admin_user -p
Enter password: admin_password
Welcome to the MySQL monitor.
Commands end with ; or \g.
Your MySQL connection id is 103 to server version: 5.0.24a-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> create database slimserver;
Query OK, 1 row affected (0.22 sec)
mysql> grant all on slimserver.* to slimserver identified by 'slimserver_password';
Query OK, 0 rows affected (0.13 sec)
mysql> grant all on slimserver.* to slimserver@localhost identified by 'slimserver_password';
Query OK, 0 rows affected (0.13 sec)
mysql> flush privileges;
Query OK,
mysql> quit
There were also slight differences necessary in the preferences setup because MySQL socket location was different from the standard one. Here are my db entries ~/Library/Application Support/Squeezebox/server.prefs:
dbpassword: slimserver_password
dbsource: dbi:mysql:database=slimserver;mysql_socket=/var/mysql/mysql.sock
dbusername: slimserver
Notice the extra mysql_socket configuration. -
Hi,
I have written an applet with the following code that opens a simple socket. The problem is that I can only run one copy of the applet at once or I get an IOException can not create socket. Can any help me out
Thanks for any help
Joolz
//// Start Code ////
public tcpip(InetAddress ipa, int port)
Socket _given = null;
try
_given = new Socket(ipa.getHostAddress(),port);
catch(IOException e) {System.out.println("Error creating socket..");
return;
//// End Code ////Hi,
Here is the error message, I don't have access to the server.
Error creating socket java.net.connectException Connection refused connect.
Thanks
Joolz -
Sockets problem under 1.4
After upgrading to version 1.4 of the Java runtime, several of our users experience the following problem. Some of the data sent from the server seems to disappear from the socket. If I snoop on the machine, I can see the data coming in, but if I dump the raw bytes directly from the socket to a file, the data is not there. I appreciate any help. Thanks.
-Pete SpiroI think I read somewhere that there are Socket bugs in 1.4. You should check out the bug list to see if I'm right or not, and if it pertains to your problem.
Maybe you are looking for
-
Hi everyone, I created a Group left report with 4 grouping columns.Everthing is working fine but i am getting some problem with the order of the 3rd column(varchar).It is doing ascending order(As the Break order Propoerty of that column is ascending)
-
Is it possible to connect to a web Service(JAX-RPC) with a middlet?
Is it possible to connect to a web Service(JAX-RPC) with a middlet?
-
Youtube :An error occurred loading this content. Try again Later
An error occurred loading this content. Try again Later I get this message when trying to stream from youtube with my apple tv 2g since one week, i've restored with the new ios 5.1 but the problem still exists. i've tried with another ISP and the pro
-
FN button not work on satellite L745
yesterday i uninstall almost all toshiba prog's and then my FN button not work!!!!!!!!!!!! please help me this laptop not until one week
-
OCE 10g - RAC 10g Certification
Hello all; I have passed on all courses for OCP 11g certification (1z0-051, 1z0-052 and 1z0-053). I just scheduled my ADM 11g WORKSHOP II to november, 21th, in order to submit the course form, and get my OCP certification. I have passed today on RAC