I want to connect android server application with laptop client java which connected on same wifi network.
i try the following code.
laptop client code
String IPToConnect="192.168.0.";
int i=0;
Socket skt;
PrintWriter pw;
try
{
for(i=105;i<=199;i++)
{
try
{
System.out.println(i);
skt=new Socket(IPToConnect+i,4444);
pw=new PrintWriter(skt.getOutputStream(),true);
pw.write("KP");
pw.flush();
pw.close();
skt.close();
}
catch(Exception ex)
{
continue;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
and android server code
private static ServerSocket serverSocket;
private static Socket client;
private static InputStreamReader inputStreamReader;
private static BufferedReader br;
private static String message;
serverSocket = new ServerSocket(4444)
try
{
client = serverSocket.accept();
inputStreamReader = new InputStreamReader(client.getInputStream());
br = new BufferedReader(inputStreamReader);
message = br.readLine();
System.out.println(""+message);
inputStreamReader.close();
client.close();
}
catch(Exception ex)
{
System.out.println("HELLO ERROR");
}
above code working fine for me
i want the program working like this
Android mobile app and laptop connected through same wifi network
when android app start it display the laptop on list when laptop start that client application
above code working fine but it may be not work when different router use different ip addresses means not start with(192.168.0) and it send request to all device means it time consuming
so please help me to solve the problem, in short i want to list laptop on android app when laptop start it client app
thank you
Related
I can not add TCP/IP Server to the service, when closing (minimizing) the application, the server does not accept data.
How to make the data transmitted continuously?
public int onStartCommand(Intent intent, int flags, int startId) {
myServer = new Server();
myServer.start();
return Service.START_STICKY;
}
Server
private class Server extends Thread {
private Socket clientSocket;
private ServerSocket server;
private BufferedReader in;
private BufferedWriter out;
private String LOG_TAG;
#Override
public void run() {
while (true) {
try {
server = new ServerSocket(9002);
clientSocket = server.accept();
try {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
String word = in.readLine();
Log.d(LOG_TAG, "***" + word + "***");
out.write(word);
out.flush();
} finally {
System.out.println("run closed");
clientSocket.close();
in.close();
out.close();
}
} finally {
System.out.println("Server closed");
server.close();
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
So many problems with this code. Here's a list of them:
You'd need to be a foreground service, or Android will eventually kill your service.
You're making a server socket and accepting a single connection to it, then making another in a loop. That's not how you do it. You make the server socket once, and accept() for each incoming connection
As a consequence of the above, the second time will always fail, because the port won't be immediately available unless you use a socket with SO_REUSEADDR set. see the setReuseAddress call on ServerSocket
You're catching all exceptions blindly. I would highly suspect you're throwing an exception and ignoring it, causing it all to not work
This code won't work on any cellular network, as a NAT will be put between you and the world.
Even on wifi you need to make sure your network allows incoming connections to your device. The default on most home routers is not to.
I want some brief idea/links for reference to start how to connect esp8266 router/access point with an android app.In esp8266 static ip is 192.168.4.1 wants to control led blink or other feautre with an android app .
how to make establish connection between esp8266 and android app .
On Android side it's just network communication without any features. Take a look at Official Documentation and tutorials like this. Everything depends on esp8266 firmware:
if it implements HTTP web server You can use HttpUrlConnection and GET or POST requests on Android side and corresponding script on esp8266 side;
if it implements ServerSocket You can use Socket connection an implement Socket Client on Android side.
Update:
Socket communication with esp8266 You should do it in separate (not UI) thread. Full example is something like that:
class SocketClientThread implements Runnable {
DataInputStream dis;
DataOutputStream dos;
String strResponseData;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("<address>");
clientSocket = new Socket(serverAddr, <port_number - 80 in your example>);
dos = new DataOutputStream(clientSocket.getOutputStream());
dis = new DataInputStream(clientSocket.getInputStream());
// now you can write data to stream
dos.writeUTF("Hello");
// you can also read data from stream
strResponseData = dis.readUTF();
} catch (UnknownHostException ignore) {
} catch (IOException ignore) {
}
finally{
if (clientSocket != null){
try {
clientSocket.close();
}
catch (IOException ignore) {
}
}
}
}
}
And than You can use SocketClientThread this way:
Thread socketClientThread;
socketClientThread = new Thread(new SocketClientThread());
socketClientThread.start();
I'm writing an application to communicate between my smartphone and a computer using a bluetooth device.
I'm using Bluecove to manage the bluetooth on the computer, and the android API for my android device.
However, when I'm debugging, nothing happens. I think that the problem is that the UUID is wrong. I'm not sure how to get the devices to identify each other, in order to establish a connection.
I have read some other "questions" about those tags, but what I've tried didn't fix my problem:
Simple Bluetooth data receiver Android
Android: obtaining uuid of a bluetooth device
Etc...
Here's what I've written so far:
For tho android (Server) (This is the function that will make the connection)
public void connectSocket(){
blueAdapter.cancelDiscovery(); // Cancel discovery because it'll slow down the connection
final BluetoothServerSocket serverSocket;
BluetoothServerSocket sSocket= null;
try{
sSocket = blueAdapter.listenUsingRfcommWithServiceRecord("BluetoothJANE", MY_UUID);
}catch(IOException e){}
serverSocket = sSocket;
Thread acceptThread = new Thread(new Runnable() {
#Override
public void run() {
BluetoothSocket socket = null;
while(true){
try{
socket = serverSocket.accept();
}catch(IOException e){
break;
}
if(socket != null){
try{
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
} catch(IOException e){}
}
}
}
});
acceptThread.start();
}
For java app on PC (This is the constructor of the class (it's on an independent thread) that will manage the bluetooth connection)
public ModuleBluetooth() {
StreamConnectionNotifier notifier = null;
StreamConnection connection = null;
try {
blueDevice = LocalDevice.getLocalDevice();
blueDevice.setDiscoverable(DiscoveryAgent.GIAC);
String url = "btspp://localhost:" + MY_UUID.toString()
+ ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (BluetoothStateException e) {
System.out
.println("ModuleBluetooth: Error getting the bluetooth device");
} catch (IOException e) {
}
System.out.println("waiting for connection...");
try {
connection = notifier.acceptAndOpen();
System.out.println("Conenction created");
} catch (IOException e) {
System.out.println("Can not create the connection");
}
}
Could somebody please help me? Any thoughts would be very much appreciated.
I have also tried to use some functions to acquire the UUID (in android) such as, [fetchUuidsWithSdp][2] (and the related functions) but eclipse doesn't recognize that functions (It seems that they don't exist in "my" API).
http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#fetchUuidsWithSdp%28%29
Try this example, http://luugiathuy.com/2011/02/android-java-bluetooth/ . I also had problem related to UUID, in this example, Converting UUID to 00001101-0000-1000-8000-00805F9B34FB worked out of the box. See this link: http://www.avetana-gmbh.de/avetana-gmbh/produkte/doc/javax/bluetooth/UUID.html
I'm trying to build a chat program. I wrote the code and everything worked and still works great when I'm using my computer and connecting using 127.0.0.1. I also succeeded to connect successfully between my laptop and my computer, which run on the same router. (I used an internal IP address to do this, 10.0.0.3).
Now I'm trying to make a connection between my router and other routers. And to this I'm trying to connect to an external IP address. I do the port forwarding part through my router and I also made a static IP. When I run the code I always get a "connection refused error".
Here is the code:
MainServer.java:
import java.util.*;
import java.io.*;
import java.net.*;
public class MainServer {
private ArrayList<Socket> sockets;
public MainServer() {
ServerSocket server_socket;
try {
server_socket = new ServerSocket(5005);
sockets = new ArrayList<Socket>();
System.out.println("server is now running");
while(true) {
Socket socket = server_socket.accept();
sockets.add(socket);
try {
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println("---you are connected to the server---\r\n");
writer.flush();
} catch(Exception e) {e.printStackTrace();}
System.out.println("server connected to " + socket.getInetAddress());
Reader reader = new Reader(socket);
Thread thread = new Thread(reader);
thread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
MainServer server = new MainServer();
}
class Reader implements Runnable {
Socket socket;
public Reader(Socket socket) {
this.socket=socket;
}
public void run() {
while(true) {
try {
InputStreamReader stream_reader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(stream_reader);
while(true) {
String str = reader.readLine();
if(str==null)
continue;
System.out.println("message from the client " + socket.getInetAddress() + ": " + str);
send_back_message(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void send_back_message(String str) {
try {
for(Socket send_to_socket: sockets) {
PrintWriter writer = new PrintWriter(send_to_socket.getOutputStream());
writer.println(send_to_socket.getInetAddress()+ ": " + str);
writer.flush();
}
} catch(Exception e) {e.printStackTrace();}
}
}
}
Client.java:
public Client() {
frame = new JFrame();
JPanel panel = new JPanel();
chat = new JTextArea(20,40);
chat.setEditable(false);
JScrollPane scroll = new JScrollPane(chat);
text = new JTextField(32);
JButton send = new JButton("Send");
send.addActionListener(new SendButtonListener());
panel.add(scroll);
panel.add(text);
panel.add(send);
frame.getContentPane().add(panel);
frame.setSize(500,500);
frame.setVisible(true);
try {
socket = new Socket("77.126.189.65",5005);
} catch (Exception e) {
e.printStackTrace();
}
Thread thread = new Thread(new ClientReader());
thread.start();
}
public static void main(String[] args) {
Client client = new Client();
}
class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(text.getText());
writer.flush();
text.setText("");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class ClientReader implements Runnable {
public void run() {
try {
InputStreamReader stream_reader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(stream_reader);
while(true) {
String str = reader.readLine();
if(str==null)
continue;
chat.setText(chat.getText() + str + "\r\n" );
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I also tried this tool. When I run the MainServer file and try the tool, I get a positive answer. I also get a positive on my own Eclipse. When my MainServer makes a successful connection, it prints a message about it using these lines:
Socket socket = server_socket.accept();
System.out.println("server connected to " + socket.getInetAddress());
So every time I'm clicking the "check" button in the tool above, I get a message in my Eclipse console (system.out.println part):
server connected to /69.163.149.200
Therefore I think the problem is probably not connected to the MainServer or the portforwading/firewall/static IP.
I also thought maybe the problem occurs because I'm trying connecting from my own router device to my own router. I will leave the MainServer file open for the next half hour so if someone can run the Client.java on his computer it will be helpful.
What you trying to do is a bit weird but it is possible.
You just need to know if your router supports NAT Loopback / NAT Reflection and activate it.
NAT-loopback
Also known as NAT-hairpinning or NAT-reflection. NAT-loopback is a
feature in many consumer routers which allows a user to connect to
its own public IP address from inside the LAN-network. This is
especially useful when a website (with domain) is hosted at that IP
address.
You won't be able to do this without configuring your router appropriately. Most routers do not allow (by default) incoming connections on their external (WAN) port. If you want to allow this, you'll need to go into your router configuration and configure it to allow connections on the external IP for the specific port you are using. Then, you'll have to configure the router to redirect that incoming connection from the external IP address/port to the internal IP address/port of your actual server.
This is frequently how online gamers set up servers in their own home. It is also how many people connect to their own internal networks from the outside world.
Before anything, set up a static IP (like 192.168.1.6) internally.
If youu want to connect via an external IP, there are two ways:
If you have a router, use port forwarding.
If you have a dongle, no need to port forward; you can directly access the server. Just give the dongle's external IP (to find that, use a what's-my-IP service like this one) and a port number (any). (Dongles are not blocked by any ISP.)
You can add your internal IP address along with your server name to /etc/hosts, for example, if you have external IP 10. 10. 123. 123, and with the server name YOURCOMPUTER_1.XXX.XXX, you want to connect inside network, you can add:
127.0.0.1 YOURCOMPUTER_1.XXX.XXX to your /etc/hosts
I am learning currently about client server communication using Java through sockets.
First of all I retrieve my own machine's IP Address using following code.
InetAddress ownIP=InetAddress.getLocalHost();
//the result being 192.168.56.1
Now I write the simple client server application using the above mentioned address as follow
public class SimpleClientServer {
public static void main(String[] args)
{
//sending "Hello World" to the server
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
clientSocket = new Socket("192.168.56.1", 16000);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
out.println("Hello World");
out.close();
in.close();
clientSocket.close();
}
catch(IOException e)
{
System.err.println("Error occured " + e);
}
}
}
The result hower reads a follow.
Error occured java.net.ConnectException: Connection refused: connect
What is the reason for this. Is it just the wrong host address?
From the code you have given you seem to suggest that there is currently nothing listening on port 16000 for the socket to connect to.
If this is the case you need to implement something like
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(16000);
}
catch (IOException e) {
System.err.println("Could not listen on port: 16000.");
System.exit(1);
}
More information can be found in the Java online documentation and a full example is included.
With sockets, no matter what language you're using, you either initiate a connection with socket_connect or you listen and accept with socket_listen and socket_accept. Your socket_connect call is trying to connect to an ip address that doesn't seem to be listening to anything.