This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm writing simple client - server application but I have stupid problem with this (it simplify example (everything is ok when i don't use java serialization)):
ServerSocket serversocket=null;
Socket socket=null;
String slowo=null;
try {
serversocket=new ServerSocket(8877);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
slowo=(String)ois.readObject();
My compiler shows:
Serwer.java:51: cannot find symbol
symbol : variable ois
location: class Serwer
slowo=(String)ois.readObject();
^
1 error
Can anyone help?
I have one more question. Why this program don't send messages ?
Serwer.java :
public class Serwer {
public static void main(String[] args) {
ServerSocket serversocket=null;
Socket socket=null;
InputStream we=null;
OutputStream wy=null;
BufferedReader odczyt=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
String tekst=null;
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
try {
serversocket=new ServerSocket(8877);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//slowo=(String)ois.readObject();
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(slowo==null || slowo.equals("end")) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
else if(slowo!=null) {
System.out.println(slowo);
}
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Klient.java :
public class Klient {
public static void main(String[] args) {
Socket socket=null;
InputStream we=null;
OutputStream wy=null;
BufferedReader odczyt=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
String tekst=null;
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
try {
socket=new Socket("localhost", 8877);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(slowo==null || slowo.equals("end")) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
else if(slowo!=null) {
System.out.println(slowo);
}
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
It's out of scope by the time you get to line 51 because you declare it in the previous try.
Move the declaration outside of both, or write the code differently.
I consider this style to be cluttered and hard to read. I'd write it like this:
ServerSocket serversocket=null;
String slowo="";
try {
serversocket=new ServerSocket(8877);
Socket socket = serversocket.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
slowo=(String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(serversocket);
}
Don't let a bad IDE write bad code for you.
You should close your socket in a finally block.
Related
I am trying to read some data via a GET request as
URL corpusDbUrl = null;
try {
corpusDbUrl = new URL("http://xxx.cc.ww.tt:1234/erwet/erherh/iouiiu");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URLConnection corpusDbConn = null;
try {
corpusDbConn = corpusDbUrl.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(corpusDbConn.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String inputLine="";
try {
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
} catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace();
}
and i get
java.net.SocketException: Network is unreachable
but when i try the URL in browser, it works just fine. What am i doing wrong?
I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
I'm writing simple client - server application. Everything is ok but when i change InputStream and OutputStream to ObjectOutputStream and ObjectInputStream my application doesn't send the messages. Can anyone help me and show me the problem ?
Here is the Serwer.java:
class InWorke implements Runnable{
BufferedReader odczyt=null;
String slowo;
ObjectInputStream ois=null;
Message message;
InWorke(ObjectInputStream ois) {
this.ois=ois;
}
public void run() {
while(true) {
try {
slowo = (String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(slowo);
Thread.yield();
} }
}
class OutWorke implements Runnable{
Socket socket=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
Message message; // it is the simple class to serialization
ObjectOutputStream oos;
OutWorke(Socket socket,ObjectOutputStream oos) {
this.socket=socket;
this.oos=oos;
}
public void run() {
while(true) {
odczytWe=new BufferedReader(new InputStreamReader(System.in));
try {
slowo=odczytWe.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(slowo);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread.yield();
}
}
}
public class Klient {
public static void main(String[] args) {
Socket socket=null;
ExecutorService exec=Executors.newCachedThreadPool();
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
try {
socket=new Socket("localhost", 8881);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//we=socket.getInputStream();
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//wy=socket.getOutputStream();
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.execute(new OutWorke(socket, oos));
exec.execute(new InWorke(ois));
}
}
Klient.java:
class InWorker implements Runnable{
Socket socket=null;
//InputStream we=null;
//OutputStream wy=null;
String slowo=null;
BufferedReader odczyt=null;
ObjectOutputStream oos;
ObjectInputStream ois;
Message message=null;
InWorker(Socket socket,ObjectInputStream ois) {
this.socket=socket;
this.ois=ois;
}
public void run() {
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(slowo);
Thread.yield();
}
}
}
class OutWorker implements Runnable{
DataOutputStream zapis=null;
BufferedReader odczyt=null;
//OutputStream wy=null;
String tekst=null;
ObjectOutputStream oos=null;
Message message;
OutWorker(ObjectOutputStream oos) {
this.oos=oos;
}
public void run() {
while(true) {
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread.yield();
}
}
}
public class Serwer {
public static void main(String[] args) {
ServerSocket serversocket=null;
Socket socket=null;
//InputStream we=null;
//OutputStream wy=null;
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
ExecutorService exec=Executors.newCachedThreadPool();
try {
serversocket=new ServerSocket(8881);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.execute(new InWorker(socket, ois));
exec.execute(new OutWorker(oos));
}
}
Check constructor of ObjectInputStream: constructor.
It says:
This constructor will block until the corresponding ObjectOutputStream
has written and flushed the header.
So you need to create and flush corresponding ObjectOutputStream. Now you are creating ObjectInputStreams before output stream for both server and client. They block programs because no output stream is created. You should create output streams first, call flush on them and only then create input streams.
The root issue is just as Nikita points out. The implementation solution is to have the server and client get the input and output streams in the opposite order. If one is getting the inputstream first have the other get the outputstream, etc. I switched the client to get the outputstream first and it all works. I then put it back and change the Server and it all works that way to... you can choose which to change.
For Reference:
http://docs.oracle.com/javase/6/docs/api/index.html?java/io/ObjectOutputStream.html
I am creating a desktop application in which multiple clients have to connect to the server using socket connection between them. I successfully connected them but the problem occurs when i connect multiple client simultaneously to the server, sever got an error "socket write error"
my code is below plz suggest me an answer..
public class SocketConnection implements Runnable {
// password of oracle database
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
Socket clientSocket = null;
DBConnection dbConnection;
public SocketConnection() {
// TODO Auto-generated constructor stub
dbConnection = new DBConnection();
if (con != null) {
serverSocket = dbConnection.createSocket();
if (serverSocket != null) {
System.out.println("Server Started. Looking for the connections.");
System.out.println("Listening Port:8888.......");
}
Thread t = new Thread(this);
t.start();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Connection Accepted");
Connect m_connect = new Connect(clientSocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Connect implements Runnable {
Socket clientSocket = null;
Thread t = null;
private ResultSet res1;
private ResultSet res2;
Statement stmt;
private File mkFolder;
public Connect(Socket clientSocke) {
// TODO Auto-generated constructor stub
this.clientSocket = clientSocke;
try {
stmt = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(
clientSocket.getOutputStream());
System.out.println("Connection established::"
+ clientSocket.getInetAddress());
String pass = dataInputStream.readUTF();
System.out.println(pass);
if (pass.equals("1")) {
//here is read n write operation
} else if (pass.equals("3")) {
//here is read n write operation
} else if (pass.equals("2")) {
//here is read n write operation
} else if (pass.equals("4")) {
//here is read n write operation
} else if (pass.equals("5")) {
//here is read n write operation
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Why you are doing this in that low-level way? Choose an well documented API and communicate through it!
Did you already read articles like this: Multithread client server chat on sockets. Load test. recv failed
Having some issue with Android 2.3 not picking up the Content-Encoding header from our server.
See http://pastebin.com/v0Jvn0nD for a comparison with 2.2 and 2.3.
So, I am trying to get a workaround so Android can handle the GZIP, at the moment it just fails. Here is the connection logic:
Any help would be cool. Many thanks
URL test = null;
try {
test = new URL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection connection = null;
try {
connection = test.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = null;
try {
stream = connection.getInputStream();
Log.d("HttpHelper","getContentEncoding: " + connection.getContentEncoding()); // RETURNING NULL ON 2.3
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ("gzip".equals(connection.getContentEncoding())) { // NULL HERE ON 2.3
try {
stream = new GZIPInputStream(stream);
responseString = textHelper.getText(stream);
globallistener.onComplete(responseString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}