I am writting simple program to connect server by socket in android.
But when i try to read data from socket's outputstream it will send automatically RST request. so my connection gets closed. but i want my connection to open always.
Please any one help me.
Thank you.
try {
Socket socket = new Socket("xxx.xxx.x.xx", 9083);
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println("Testing");
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String readObject = reader.readLine();
System.out.println(readObject);
} catch (Exception e) {
e.printStackTrace();
}
The most usual reason for 'connection reset' is that you have written to a connection that has already been closed by the other end. In other words, an application protocol error.
Related
I am currently trying to open a socket in android, but my code keeps sticking at one sentence.
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void run(){
Log.i("DebugMessage", "ServerThread received pulse. Trying to open socket now!");
try{
serverSocket = new ServerSocket(25555);
Log.i("DebugMessage", "serverSocket is open, waiting for the clientSocket.");
clientSocket = serverSocket.accept();
Log.i("DebugMessage", "serverSocket and clientSocket are both open! Waiting for in-/output!");
in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
String input = in.readLine();
out.println("received: " + input);
in.close();
out.close();
} catch(Exception e) {
Log.i("DebugMessage", "Failed to open socket!");
e.printStackTrace();
}
}
At clientSocket = serverSocket.accept(); it keeps sticking.
Now I have seen this question a few other times, but the answers given were totally different.
Here is being said that it is about his code, and here is being said that the problem is with the emulator. Now my question is, is my problem with the emulator or my code, and if it is with my code, how is it possible to fix it?
By the way, I have added these lines to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
The answer of FD_ is correct but i want to clarify it a bit. accept() calls wait(). So the thread will wait for a connection.
You may want to call such code from a other thread.
ServerSocket.accept() waits until a device connects to the socket's port (25555 in your case) on your device's ip address. It will only proceed and return a Socket when there is a new connection.
You'll find more information in the docs.
Below code is implemented in AsynTask and with try-catch. I want to interrupt bufferreader.readline() if server does not respond with in Specified time. How can I achieve this?
Socket tcpSocket = new Socket();
tcpSocket.connect(new InetSocketAddress("mydomain.com", 5000),
SOCK_TIMEOUT);
InputStream inputStream = tcpSocket.getInputStream();
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(inputStream));
String jsonData = bufferReader.readLine(); //blocks here
Simply close the socket and it will return with socket exception.
I've prepared socket client connection like this:
Socket socket = new Socket();
socket.setSoTimeout(500);
hostname = "XX.YY.ZZ.XX";
socket.connect(new InetSocketAddress(hostname, port), 6000);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
false);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
and I read data using i.e. this code:
if (in.ready() == true) {
String message = in.readLine();
Log.e("MyApplication", "data=" + message);
}
When I look in logcat I see ? char instead of every national characters.
I'm sure data sending to my android application is in utf-8 charset therefore I tried to use code like this:
UTF8Str = new String(message.getBytes(),"UTF-8");
or creating BufferReader like this:
in = new BufferedReader(new InputStreamReader(
socket.getInputStream(),"UTF-8"));
but everything without success.
Can somebody help me resolve problem conversion chars to display them in logcat as nationals (my main goal is to display them in TextView). Everything worked two weeks ago but after some Ecclipse reconfiguration (I can't back to old settings) stoped.
~Artik
I've got Android device acting as a client, the PC is a Bluetooth Server, using Bluecove library
Code snippet from the client:
btSocket = serverBt.createRfcommSocketToServiceRecord(myUuid);
btAdapter.cancelDiscovery();
btSocket.connect();
InputStream in = btSocket.getInputStream();
OutputStream out = btSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out);
InputStreamReader isr = new InputStreamReader(in);
osw.write(55);
osw.flush();
out.flush();
//osw.close();
logTheEvent("Stuff got written, now waiting for the response.");
int dummy = isr.read();
logTheEvent("Servers response: "+ new Integer(dummy).toString());
And the server:
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString, Connector.READ_WRITE );
StreamConnection incomingConnection=streamConnNotifier.acceptAndOpen();
InputStream in = incomingConnection.openInputStream();
OutputStream out = incomingConnection.openOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(out);
InputStreamReader isr = new InputStreamReader(in);
int fromClient = isr.read();
System.out.println("Got from client " + new Integer(fromClient).toString());
osw.write(999);
When the osw.close(); at the client is uncommented, the message gets transferred to the server, however, client is then unable to receive the response, IOException with message "socket already closed" is thrown.
However, when osw.close(); is commented, both client and server freeze:
A. Client hangs on reading server's response of course
B. Server hangs on streamConnNotifier.acceptAndOpen();
What should be done to enable two-way communication?
Is my code, or PC Bluetoototh stack, or bluecove to blame?
Bluetooth uses buffered output. That means there is a small memory location that contains all of the data you write to the stream. When this memory location gets full, it writes the buffer data to the socket in a packet. When you prematurely close the socket, that buffer gets wiped, and the data is gone.
In order to force the stream to write, try calling flush()
Something else you could do is set the buffer size to be very small, so data always gets written. The performance won't be very good if you do this, though.
Unfortunately, I don't have all of the code I wrote, but there's a base project here
public void sendToServer(String fileToSend, String ip, int sendPort)
{
int port = sendPort;
String url = ip;
File file = new File(fileToSend);
String fileName = file.getName();
Socket sock;
try {
sock = new Socket(url,port);
//Send the file name
OutputStream socketStream = sock.getOutputStream();
ObjectOutput objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(fileName);
//Send File
byte [] mybytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
fileSentOkay();
os.flush();
sock.close();
} catch (UnknownHostException e) {
hostNotFound();
} catch (IOException e) {
hostNotFound();
}
}
When I try to send something to the server when the server isn't listening for the connection, the phone keeps attempting to send the file. As a result of this, my Android program will eventually force close.
How could I set a time out for this to happen? Would I have to use something like setSoTimeout() on the socket that is sending the data?
First: Just in case: Don't do network stuff on the UI Thread. Bad Things will happen (tm)
Second: setSoTimeout() should give you a timeout in case the server accepts the connection, but does not reply (or in case there is no reply from the network at all). In case the connection is rejected the socket should fail significantly faster.
Edit: In case the constructor of the Socket class is already taking that long, try using the connect(SocketAddress, int) method. Use InetSocketAddress as parameter:
Socket s = new Socket();
s.connect(..., 1000);