I have set up a server on my computer in java, and the client is my android phone.
I am trying to simulate the mouse behavior in my app but the problem is even though at the first minutes everything runs smoothly, in the end there is a huge delay between client and server.
Server code
try {
System.out.println(InetAddress.getLocalHost());
serverSocket = new ServerSocket(4444); // Server socket
serverSocket.setReceiveBufferSize(10000);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
try {
clientSocket = serverSocket.accept(); // accept the client connection
System.out.println("connection initiated");
DataInputStream din = new DataInputStream(clientSocket.getInputStream());
DataOutputStream dout= new DataOutputStream(clientSocket.getOutputStream());
/* do my things here */
din.close();
dout.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading "+ex);
}
Client code
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
//Inet4Address.getLocalHost().toString(); //InetAddress.getLocalHost().getHostAddress().toString();
System.out.println(dstAddress);
socket = new Socket(dstAddress, dstPort);
socket.setSendBufferSize(10000);
DataInputStream din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF(kappa);
response = "sent to server";
String msg = din.readUTF();
response += msg;
din.close();
dout.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = e.toString();
}
return null;
}
(kappa is a global string that i modify each time.)
What might be the case?
Problem is solved, i changed to udp connection and now there is no delay
Related
i am making a chat application for android using UDP.
Everything works fine in lan devices, I can send and receive messages from client and from server.
When i connect to an other network with my android, i can send messages, the server receives them but the response is never received on android.
Client Receive code
Runnable periodicTask = new Runnable() {
public void run() {
// Invoke method(s) to do the work
System.out.println("Waiting for data");
byte[] receiveData = new byte[2028];
byte[] sendData = new byte[2028];
boolean portTaken=false;
DatagramSocket serverSocket=null;
ServerSocket socket = null;
try {
socket = new ServerSocket(6667);
} catch (IOException e) {
System.out.println("ERRORRRRRRRRRRRRRR");
} finally {
if (socket != null)
try {
socket.close();
serverSocket= new DatagramSocket(6667);
} catch (IOException e) { e.printStackTrace(); }
}
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
try {
serverSocket.receive(receivePacket);
System.out.println("GOT THEM!");
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayInputStream in = new ByteArrayInputStream(receiveData);
ObjectInputStream is = null;
try {
is = new ObjectInputStream(in);
} catch (IOException e) {
e.printStackTrace();
}
Data student = null;
try {
student = (Data) is.readObject();
l.add(student.toString());
mHandler.sendEmptyMessage(0);
System.out.println(student);
serverSocket.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Server Send Code
for (DatagramPacket packet:clients){
if (!packet.getAddress().equals(receivePacket.getAddress())){
System.out.println("current ip address " + receivePacket.getAddress());
System.out.println("Sending to " + packet.getAddress());
DatagramSocket s = new DatagramSocket();
InetAddress local =packet.getAddress();//editTextAddress.getText().toString());//InetAddress.getByName("192.168.1.74");
System.out.println(local.toString());
//int msg_length =student.//sentence.length();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outputStream);
os.writeObject(student);
byte[] data2 = outputStream.toByteArray();
int msg_length =data2.length;
DatagramPacket p = new DatagramPacket(data2, msg_length, local,
6667);
s.send(p);
s.close();
}
What might be the case ?
Thank you for your time
I attempting to build a remote controller for my laptop using my phone.
I written a server application that running on my laptop, the remote app used as a client to the server application.
I want to implement a mouse pad, the problem is when I am moving my finger over the "touch pad" too fast, I am receiving read time out on server side after few iterations.
Server code
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(20);
Runnable serverTask = new Runnable()
{
#Override
public void run()
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(DEFAULT_PORT);
serverSocket.setReuseAddress(true);
_working = true;
while (_working)
{
Socket clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(10000);
clientProcessingPool.submit(new ClientTask(clientSocket));
}
}
catch (IOException e)
{
System.err.println("Unable to process client request");
e.printStackTrace();
}
finally
{
try
{
if (serverSocket != null)
{
serverSocket.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
private class ClientTask implements Runnable
{
private final Socket clientSocket;
private ClientTask(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
System.out.println("Got a client !");
try
{
System.out.println("Connected!");
DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());
String request = dIn.readUTF();
parseRequest(request);
System.out.println("request=" + request);
dOut.writeUTF("Got the command");
dOut.flush(); // Send off the data
dIn.close();
dOut.close();
clientSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I thought maybe I will send the requests only if the distance from the starting position to end position is bigger than STEPS(a constant) and only then send the request. But I think the mouse won`t move fluidly.
Thanks.
RXAndroid and RXJava are perfect for asynchronously handling these request and will allow you to add a debounce to the frequent requests. Check out Reactive.io
I tested many ways and finally asked this question. as many of articles mentioned in wifi-direct all clients know group owner's IP and can use this ip to send a message and group owner will save clients ip address. but I can't send a message from group owner to client like that client sent first time. I faced with this error's:
first:
failed to connect to /192.168.49.24 (port 8988) after 5000ms: isConnected failed:
EHOSTUNREACH (No route to host).
after change code:
first error + bind failed: EADDRINUSE (Address already in use).
My AsyncTask to retrieve :
#Override
protected String doInBackground(Void... params) {
ServerSocket serverSocket = null;
Socket client = null;
DataInputStream inputstream = null;
try {
serverSocket = new ServerSocket(8988);
client = serverSocket.accept();
inputstream = new DataInputStream(client.getInputStream());
String str = inputstream.readUTF();
String IP = client.getInetAddress().toString();
serverSocket.close();
return IP+"+"+str;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}finally{
if(inputstream != null){
try{
inputstream.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(client != null){
try{
client.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(serverSocket != null){
try{
serverSocket.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
}
}
and my IntentService to send messages:
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_IP)) {
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Log.e("DAVUD","Host:"+ host);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Log.e("DAVUD","Port:"+ port);
DataOutputStream stream = null;
try {
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
stream = new DataOutputStream(socket.getOutputStream());
String str = intent.getStringExtra("message");
stream.writeUTF(str);
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
and some other codes I tested... There is another question asked same this but not answered(android-wifi-direct-how-to-send-data-from-group-owner-to-the-clients) this project based on wifiDirectDemo Simple. Please help I really need it.
After one year I sew my question again. the problem was not about wifi or connection. it's about string parsing. where a line in doInBackground is:
return IP+"+"+str
and in onPostExecute I parsed and get ip from returned string; but parse code was not correct. so returns:
192.168.49.24
instead of:
192.168.49.241
where two of them is valid ips I am not thought parse logic had problem. I changed code and used String[] instead of String.
Since many days i am going through many examples and questions related to my issue but nothing helps!
Aim
two way communication between pc(windows) and android (like passing msg to pc and acknowledgement from pc)
What i have done till now
I am able to send String to pc(windows) from my android device using bluetooth.
here is the code i used
private String sendFile(String mac_address, String device_name) {
// TODO Auto-generated method stub
String result="";
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(mac_address);
Log.d("BT_SENDING_FILE",device_name+" "+mac_address);
try {
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
btSocket = (BluetoothSocket) m.invoke(device, 1);
if(!btSocket.isConnected()){
Log.d(" is connected Status",""+btSocket.isConnected());
// device.createInsecureRfcommSocketToServiceRecord(UUID);
}
btAdapter.cancelDiscovery();
try{
btSocket.connect();
}catch(IOException e){
btSocket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
btSocket.connect();
Log.d("fall back","in catch clause");
}
byte[] msgBuffer = stringToSend.getBytes();
outStream = btSocket.getOutputStream();
outStream.write(msgBuffer);
if (outStream != null) {
outStream.flush();
}
result = "sent";
outStream.close();
btSocket.close();
Log.d("BLUETOOTH","Closing Socket");
} catch (Exception e) {
System.out.println(e);
Log.d("BLUETOOTH","exception while sending through bluetooth");
result = "failed";
e.getLocalizedMessage();
} finally{}
return result;
}
this is running good without any problem.
Problem
But i am not able to receive any String from pc to android device. I have tried many things
I have tried this
BluetoothSocket socket = null;
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
while (true) {
try {
// Creating a new listening server socket
Log.d("BT", ".....Initializing RFCOMM SERVER....");
mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord("Bluetooth", MY_UUID);
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d("Socket","listening...");
socket = mmServerSocket.accept(120000);
} catch (Exception e) {
}
try {
Log.d("Socket", "Closing Server Socket.....");
mmServerSocket.close();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
Log.d("BT","IO stream init");
DataInputStream mmInStream = new DataInputStream(tmpIn);
DataOutputStream mmOutStream = new DataOutputStream(tmpOut);
// use the Input Stream to take the string from the client whoever is connecting
//similarly use the output stream to send the data to the client
StringBuilder sb = new StringBuilder();
while((ch = mmInStream.read())!= -1)
sb.append((char)ch);
String res = sb.toString();
Log.d("BT",res);
tv_response.setText(res));
} catch (Exception e) {
//catch your exception here
e.printStackTrace();
Log.d("Exception","some thing went wrong");
e.getLocalizedMessage();
}
}
}
I am using Blue Cove in windows. I HAVE GONE THROUGH BLUETOOTH CHAT SAMPLE PROJECT but dont understand any thing
your help is appreciated
thank you
i tried following code and it was successful. it may help you
BluetoothSocket socket = null;
while (true) {
try {
Log.i(ACCEPT_TAG, "Listening for a connection...");
socket = mServerSocket.accept();
Log.i(ACCEPT_TAG, "Connected to " + socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
// Read the incoming string.
String buffer;
DataInputStream in = new DataInputStream(socket.getInputStream());
buffer = in.readUTF();
Intent i = new Intent(MESSAGE_RECEIVED_INTENT);
i.putExtra("Message", String.format("%s", buffer));
Log.d("BT response is",buffer);
c.sendBroadcast(i);
} catch (IOException e) {
Log.e(ACCEPT_TAG, "Error obtaining InputStream from socket");
e.printStackTrace();
}
try {
mServerSocket.close();
} catch (IOException e) { }
break;
}
}
Be sure that your device is visible to all i.e scan mode is BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE
else use this code
public void requestBTDiscoverable() {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivityForResult(i, REQ);
int result = 0;
this.onActivityResult(REQ, result, i);
Log.i(TAG, "Bluetooth discoverability enabled");
}
Hey community I have the following ServerSocket which should listen to port 53000 and log any received data. However, I cannot seem to get past the server.accept() blocking call.
public void run() {
SocketServer server = new ServerSocket(53000);
//---buffer store for the stream---
byte[] buffer = new byte[1024];
//---bytes returned from read()---
int bytes;
//---keep listening to the InputStream until an
// exception occurs---
while (true) {
try {
socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e){
server.close();
Log.e(TAG, e.getMessage());
}
}
}
I have also given the application the INTERNET permission in the Manifest file.
()
To add to the mystery, I have also verified client responses get sent to that port.
Is there something in particular I need to do to make this work?
Thanks.
Your code is very messy and won't even compile. I made some adjustments so that i could test your code, and it's working fine. Here is the test application I used:
package com.test.stackoverflow
import java.io.BufferedReader;
public class ServerSocketTestActivity extends Activity {
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
server = new ServerSocket(53000);
while (true) {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Using this code and netcat running via adb shell I was able to connect and communicate with the application.
When working with The Client Declare these methods
To access Streams
// gets the input stream // ObjectInputStream input;
// gets the output stream // ObjectOutputStream output;
// ServerSocket server;
// Socket connection;
maybe you have a another class to access the socket;
server = new ServerSocket(5001, 100);
// step 1 create socket connection
server = new ServerSocket(5001, 100);
while(the condition is true)
// step 2 wait for connection
// step 3 get streams
// step 4 : process the connection
// step 5 : close connection