At the moment I'm trying to develop an Android Application for Instant Messaging. I want to use ejabberd for this on an Ubuntu Server. There is just one problem.
When I try to connect to my ejabberd first with this xml-line:
<stream:stream to='x.x.x.x' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>
it takes very long to receive the answer (about 20 seconds, sometimes longer).
I just have this problem, when I send some "good" data to the Server. Sending some "bad" data, i receive the Error message very fast.
It's performed by an Android IntentService
I will Post my Code here too:
the attributes:
private Socket socket;
private String host = "x.x.x.x";
private int port = 5222;
private OutputStream out = null;
private String in = null;
the doInBackground():
this.socket = new Socket(host,port);
if(!this.socket.isConnected()){
Log.e("Socket","Socket nicht geöffnet");
}else{
Log.e("Socket","Socket erfolgreich geöffnet");
//create output stream
try {
this.out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//write to output stream
StringBuffer stringbuffer = new StringBuffer();
stringbuffer.append("<stream:stream to='5.175.8.41' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>");
//convert into bits and give it to outputstream
try {
this.out.write(String.valueOf(stringbuffer).getBytes("UTF-8"),0,String.valueOf(stringbuffer).getBytes().length);
out.flush();
Log.e("Connecting-out","Erstes Tupel erfolgreich gesendet.");
} catch (IOException e) {
e.printStackTrace();
}
//receive the answer from server
try {
Log.e("lol","lol");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"),200);
StringBuilder builder = new StringBuilder();
String aux;
aux = in.readLine();
this.in = builder.toString();
Log.e("...",aux);
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Connecting-in",in);
i think especially these lines
StringBuilder builder = new StringBuilder();
String aux;
aux = in.readLine();
this.in = builder.toString();
take very long. But the strange thing is , that the Error message is read very fast. So it has to be the Server?
Can someone please help me?
Thanks in advance :)
You used readLine() and it waits for new line character.
On error, server generally disconnects the connection.
It is why you get error answer immediately.
I suggest you not using readLine().
Related
I wrote a basic code to read a line from a server and used readline() to see what will be the output.
But some unidentified symbols are being returned and I don't know what they are or why they are coming. I could use some help Thanks.
I've also provided a link to the photo of what is being returned.
https://drive.google.com/file/d/1AM27ZAKy4iJNJH8vpY1XGy-E0YAxZyNw/view?usp=sharing
This the code
try {
Socket socket = new Socket("192.168.0.14", 1099);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String data;
if (socket.isConnected()) {
data = reader.readLine();
serverData.setText(data);
}
} catch (IOException e){
e.printStackTrace();
}
Hello I have an app that connect to a remote server using sockets
socket = new Socket();
socket.connect(new InetSocketAddress(Ip, portNum), 7000);
I have 2 methods send & receive
the scenario in send is
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
in method receive
String msg = "";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (in.ready()) {
msg = msg + (char) in.read();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
in AsyncTask of a different class I call
send();
String response=receive();
The above code is not sending or receiving without a wait period
i.e
Thread.sleep(2000);
I know sleep is a bad approach
what is the best scenario should I use?
Is it better to make an AsyncTask within send method and another one for receive method.
Here is where I use sleep and what data send & receive
client.send(some sql statement representED as json format);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// sql select result represented as json
String RESULT = client.recive();
Likely your server is not listening before you try to connect. Though this is unclear from the code you have posted. You'll need to show both server and client code there.
i have this assignment where i am supposed to write a proxy server that uses java sockets to handle get requests from a client. I am now stuck and have been looking all over google to find the answer but without success.
Christoffers solution helped my with my first problem. Now that i have updated the code this is what i am using.
The problem is that it only downloads parts of most webpages before it gets stuck on sending the packets back to the client loop. At the moment I cant explain why it is behaving the way it is.
public class MyProxyServer {
//Set the portnumber to open socket on
public static final int portNumber = 5555;
public static void main(String[] args){
//create and start the proxy
MyProxyServer myProxyServer = new MyProxyServer();
myProxyServer.start();
}
public void start(){
System.out.println("Starting MyProxyServer ...");
try {
//create the socket
ServerSocket serverSocket = new ServerSocket(MyProxyServer.portNumber);
while(true)
{
//wait for a client to connect
Socket clientSocket = serverSocket.accept();
//create a reader to read the instream
BufferedReader inreader = new BufferedReader( new InputStreamReader(clientSocket.getInputStream(), "ISO-8859-1"));
//string builder for preformance when we loop over the inputstream and read lines
StringBuilder builder = new StringBuilder();
String host = "";
for (String buffer; (buffer = inreader.readLine()) != null;) {
if (buffer.isEmpty()) break;
builder.append(buffer.replaceAll("keep-alive", "close"));
if(buffer.contains("Host"))
{
//parse the host
host = buffer.replaceAll("Host: ", "");
}
System.out.println(buffer);
}
String req = builder.toString();
System.out.println("finshed reading \n" + req);
System.out.println("host: " + host);
//new socket to send the information over
Socket s = new Socket(InetAddress.getByName(host), 80);
//printwriter to send text over the output stream
PrintWriter pw = new PrintWriter(s.getOutputStream());
//send the request from the client
pw.println(req+"\r\n");
pw.flush();
//create inputstream to receive the web page from the host
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
//create outputstream to send the web page to the client
BufferedOutputStream outbuffer = new BufferedOutputStream(clientSocket.getOutputStream());
byte[] bytebuffer = new byte[1024];
int bytesread;
//send the response back to the client
while((bytesread = in.read(bytebuffer)) != -1) {
System.out.println(bytesread);
outbuffer.write(bytebuffer,0, bytesread);
outbuffer.flush();
}
System.out.println("done sending");
//close the streams
inreader.close();
s.close();
pw.close();
outbuffer.close();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch(RuntimeException e){
e.printStackTrace();
}
}
}
If anyone could explain to me why i cant get it working correctly and how to solve it I would be very grateful!
Thanks in advance.
I'm building a Java client application which needs to send a message to a server and receive a response afterwards. I can send the message successfully, the problem is that I can't get the response because I get an IO exception ("Socked is closed") when trying to read the 'BufferedReader'.
This is my code, so far:
public class MyClass {
/**
* #param args the command line arguments
*/
#SuppressWarnings("empty-statement")
public static void main(String[] args) {
JSONObject j = new JSONObject();
try {
j.put("comando", 1);
j.put("versao", 1);
j.put("senha", "c4ca4238a0b923820dcc509a6f75849b");
j.put("usuario", "1");
j.put("deviceId", "1");
} catch (JSONException ex) {
System.out.println("JSON Exception reached");
}
String LoginString = "{comando':1,'versao':1,'senha':'c4ca4238a0b923820dcc509a6f75849b','usuario':'1','deviceId':'1'}";
try {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("10.1.1.12", 3333);
System.out.println("Connected to the server successfully");
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
outToServer.println(j.toString());
outToServer.close();
System.out.println("TO SERVER: " + j.toString());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String resposta = inFromServer.readLine();
System.out.println("FROM SERVER: " + resposta);
clientSocket.close();
} catch (UnknownHostException ex) {
System.out.println("Could not connect to the server [Unknown exception]");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
I know that the socket is being closed because of the OutToServer.close() but closing the stream is the only way to send the message. How should I approach this situation?
flush() is not the case when it comes with new PrintWriter(, true).
The real problem is that you are closing the PrintWriter outToServer which wraps the underlying InputStream, again, came from the Socket.
When you close the outToServer you're closing the whole socket.
You have to use Socket#shutdownOutput().
You don't even have to close the output if you want to keep the socket's in/out channels for further communications.
flush() when you are done with any writeXXX. Those writeXXX practically don't mean you sent those bytes and characters to other side of the socket.
You may have to close the output, and output only, to signal the server that you sent all you had to send. This is really a matter of the server-side socket's desire.
final Socket socket = new Socket(...);
try {
final PrintStream out = new PrintStream(socket.getOutputStream());
// write here
out.flush(); // this is important.
socket.shutdownOutput(); // half closing
// socket is still alive
// read input here
} finally {
socket.close();
}
Try to call outToServer.flush()
That will try to flush the data from the buffer, although it still not guarantees that it will be sent.
I have made an android socket client application for android 2.3.3.
It sends a XML request, and then recieves an answer back from a cobol socket server.
The application works perfectly fine, my problem is that, once my client application has read all the data, it still hangs around, waiting for the timeout limit for some reason.
Heres the code:
Socket socket = new Socket(serverIpAddress, serverPort);
socket.setSoTimeout(2000);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String request = ("Some XML Request");
out.println(request);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Nicklas", "Reader Oprettet");
Vector<String> v = new Vector<String>();
int i = 0;
Boolean KeepGoing = true;
while (KeepGoing)
{
try
{
String lol = in.readLine();
if (lol == null) { KeepGoing = false; }
v.add(new String(lol));
i++;
}
catch (Exception e)
{
Log.d("NickEEEXX", e.toString());
KeepGoing = false;
}
}
It always ends in the catch, with the exception "java.net.SocketTimeoutException" - even if it has sent and recieved the right data. This slows down the program a lot.
I am running this code as a method, not a thread, becouse i need to change the GUI in this section.
Does anyone have any ideas why it waits for the timeout?
Maybe lol is not null when there's no more data. Try checking against a blank string.