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);
Related
Can anyone suggest a good example for get an idea about creating TCP server and client with android WiFi direct to transfer data. (Actually transfering of strings not files)
Actually I did one, but I cannot get the IP of server from client side.
If server and client are connected to the same wifi network, then please try use the 192.168.1.40 IP in the client to send data to server.
For example in client:
Socket socket = new Socket("192.168.1.40", port);
Hope it helps.
package com.example.androidclient;
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
I am trying to create a server and client application on two android Phone(Nexus 4).One Phone as client and other as server. But at the server side I am getting an error of EOF exception while reading the incoming data and at the client side I am getting IO exception while writing some byte to Socket outputStream. Can someone enlighten me what I am doing wrong?
Client side Code
// Send only one byte to server
while (!Thread.currentThread().isInterrupted()) {
try {
Log.d(TAG,"Entering into the IO exception block");
byte[] image_data = new byte[3];
String send_string = new String(image_data);
// Create a Output Stream to send the bytes back to server
OutputStream out;
out = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
Log.d(TAG,"Created data output Stream");
dos.writeUTF(send_string);
/*
dos.writeInt(image_data.length);
dos.write(image_data, 0, image_data.length);
Log.d(TAG,"Writing the ByteArray into Socket ");
*/
out.close();
dos.flush();
dos.close();
s.close();
} catch (IOException e1) {
Log.d(TAG,"Exception while writing to Socket");
e1.printStackTrace();
}
}
Server side Code : Exception while dis.readFully(ClientByteArray)
if (s == null)
s = ss.accept();
Log.d(TAG,"Socket server is closed " + ss.isClosed() +", Recieved Buffer Size = " + ss.getReceiveBufferSize());
Log.d(TAG,"Accepted Client socket at server");
byte[] ClientByteArray = new byte[ss.getReceiveBufferSize()];
InputStream in;
in = s.getInputStream();
DataInputStream dis = new DataInputStream(in);
dis.readFully(ClientByteArray);
Log.d(TAG,"Data recieved from Client, Bytes = " + ClientByteArray.length);
You are writing with writeUTF(), so you should be reading with readUTF().
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
I am trying to send a file over bluetooth in an android device. I have done discovery, connection and have made a bluetooth socket. Problem is when i am writing the byte array in the output stream of the bluetooth socket, the recieving side does not receive anything although it accept that something is being sent.
Here's what Iam doing (bad is the bluetooth adaptor)
Please advise.
try
{
BluetoothDevice dev = bad.getRemoteDevice(a);
bad.cancelDiscovery();
dev.createRfcommSocketToServiceRecord(new UUID(1111, 2222));
Method m = dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
bs = (BluetoothSocket) m.invoke(dev, Integer.valueOf(1));
bs.connect();
tmpOut = bs.getOutputStream();
}catch(Exception e)
{
}
File f = new File(filename);
byte b[] = new byte[(int) f.length()];
try
{
FileInputStream fileInputStream = new FileInputStream(f);
fileInputStream.read(b);
}catch(IOException e)
{
Log.d(TAG, "Error converting file");
Log.d(TAG, e.getMessage());
}
try {
tmpOut.write(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am using the below code snipped to connect to the serial service in a remote Bluetooth device and it is working fine for me. Just make sure that the other device (can be mobile or PC) has a server socket for serial communication over Bluetooth (see the server side code below)
Client Side:
UUID serialUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice btDevice = btAdapter.getRemoteDevice(BTAddress); // Get the BTAddress after scan
BluetoothSocket btSocket = btDevice.createRfcommSocketToServiceRecord(SERIAL_UUID);
btSocket.connect();
InputStream iStream = btSocket.getInputStream();
OutputStream oStream = btSocket.getOutputStream();
Server Side:
UUID serialUUID = new UUID("1101", true);
String serviceURL = "btspp://localhost:" + serialUUID
+ ";name=Android BT Server;authorize=false;authenticate=false";
StreamConnectionNotifier connectionNotifier = (StreamConnectionNotifier) Connector
.open(serviceURL);
// Blocking method will wait for client to connect
StreamConnection connection = connectionNotifier.acceptAndOpen();
RemoteDevice remoteDevice = RemoteDevice.getRemoteDevice(connection);
InputStream btInput = connection.openInputStream();
OutputStream btOutput = connection.openOutputStream();
Why not use the standard api call instead of calling through reflection, eg:
BluetoothSocket socket = destination
.createRfcommSocketToServiceRecord(new UUID(...)) ;
Also your catch block is empty. Are you sure the socket was connected without any exception? Connect will throw IOException if the connection failed for some reason. See this link
It might be because dev and bs go out of scope before tmpout is used because they are declared within your try/catch block.
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.