Socket Programming in AVD - java

In this site use socket for send message to the server.
I haven't any Error in this project but I doesn't work and don't show nothings in avd, help me to run it. I think the port number or IP number is false and don't know what number is correct.
Did I need to install something?

try this in client.java
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVERPORT);
socket.connect(socketAddress);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
}
}

Related

Android Studio socket server and client send and recieve data

I'm newer programer in android .. I need help
to sending text between two phone by wifi
first : server
second :client
I'm searching more but i need Simple code and easy to help me
thnx for advance
I guess sockets is what you are looking for...
To create a socket in android the socket must be created in a thread.
Client side example:
private final String IP = "9.9.9.9";
private final int PORT = 8080;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new MainThread()).start();
}
class MainThread implements Runnable {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(IP);
socket = new Socket(address,PORT);
new Thread(new GetThread()).start();
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class GetThread implements Runnable {
#Override
public void run() {
try {
InputStreamReader isR=new InputStreamReader(socket.getInputStream());
BufferedReader bfr=new BufferedReader(isR);
while(true) {
String textMessage = bfr.readLine();
// TODO: Insert logic which use the recived message (textMessage)
}
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
In the thread, the socket is waiting for data to be sent (while(true)).
and the IP is the ip of the server (if you are connecting to your computer
with wifi, you should check your ip address with ipconfig in the command line).

android client side doesnt read after a while

It's my first question in here. I hope i can find answer. Subject is that, i have server (arduino). it send and receive data.it send data when take a data from client side(android). Android side is send data when push button. Also android has use Speech to Text (google API).So when we push button or use speechrecognation, client side send a data.But it reads socket continuously. I have two kind android device. One device work well about data receiving but it is not good about speechrecognation. One device very well about voice but after a while socket is happened useless. We must push reset button on arduino and reset android app. (My first android device version is 5.1.1 second is 6.0). Sorry for my english. I hope i can tell my problem :)
.
.
.
public void senddata(String asd){
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(asd);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
.
.
.
class ClientThread implements Runnable {
#Override
public void run() {
BufferedReader inStream = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//socket.setSoTimeout(1000);
// Get the input and output streams
inStream = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
// Confirm that the socket opened
// Read messages in a loop until disconnected
while( true){
String msg= inStream.readLine();
Log.e("GELENLER::::",msg);
gelenkomut=msg;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
gelenparse(gelenkomut);
}
});
// Send it to the UI thread
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
try {
inStream.reset();
inStream.
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Android: cannot create socket

I'm having problems when creating a socket in android. I'm using LibGDX.
#Override
public void create() {
System.out.println("Enter IP adress.");
ip = "78.61.65.198";
System.out.println("Connecting...");
socket = connection(PORT, ip);
System.out.println("Setting up InputStream");
reader = reader(socket);
System.out.println("Setting up OutputStream");
output = output(socket);
while (socket.isConnected()) {
output.println("0;" + Gdx.input.getAccelerometerX() + ";" + Gdx.input.getAccelerometerY());
}
}
public static Socket connection(int port, String ip) {
try {
return new Socket(InetAddress.getByName(ip), port);
} catch (UnknownHostException e) {
e.printStackTrace();
System.out.println("Unknown host...");
return null;
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to connect...");
return null;
}
}
public static BufferedReader reader(Socket socket) {
try {
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
System.err.println("Couldn't get inputStream...");
e.printStackTrace();
return null;
}
}
public static PrintStream output(Socket socket) {
try {
return new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get outputStream");
return null;
}
}
Server:
#Override
public void create() {
System.out.println("Creating server...");
server = hostServer(PORT);
System.out.println("Waiting for Client 1...");
client1 = waitForConnections(server);
System.out.println("Setting up input/output for client 1...");
client1Input = reader(client1);
client1Output = output(client1);
setScreen(new gameScreen(this));
}
public static ServerSocket hostServer(int port){
try {
return new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to host server!");
return null;
}
}
public static BufferedReader reader(Socket socket){
try {
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to get input stream!");
return null;
}
}
public static PrintStream output(Socket socket){
try {
return new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to create output stream!");
return null;
}
}
public static Socket waitForConnections(ServerSocket server){
try {
return server.accept();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to accept connection!");
return null;
}
}
It works when i do it with a desktop project, but when i do it with an android project, it doesn't work.
ERROR:
Let me know if anyone has similiar problems or have found a solution.
Assuming both your PC and your Android device are connected to the same LAN (connected to the same router), you should try to use the server's internal IP address (usually looks like: 10.0.0.X or 192.168.X.X), which you can find by running the ipconfig command on the command line in a Windows PC, or ifconfig on Linux/MAC. If your PC and Android device are connected to different networks then you should use the server's external IP address like you did in your example. If it is the latter you should also forward the port your using (1234) to your PC in your router.
When the server is startet on your pc, you cannot connect from another device than your pc as long as you try to connect to localhost/127.0.0.1. Only when running the app on your pc as desktop application the connection will work since client and server are on the same host. For other clients you need to connect to the local LAN IP address of your PC. When you try to connect to localhost/127.0.0.1 from your phone it is looking for a server running on the phone and this is not the case.
Is the client network connection estabished in an UI thread/activity? If so, network connection should established in a separate thread, eg. AsynTask for short operations and services for longer streaming operations. http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask

tcp connection between Android server and PC client

Server part(Android)
new Thread(new Runnable() {
public void run() {
DatagramSocket s;
try {
s = new DatagramSocket();
s.send(new DatagramPacket("aaa".getBytes(), 3, InetAddress.getByName(/* Server ip address*/), 11720));
s.close();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true)
{
try {
ServerSocket ssocket = new ServerSocket(11720);
ssocket.accept(); // Cannot make connection!!
Toast.makeText(a, "Who's coming", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
Client code (Java, PC)
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(11720);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
ds.close();
try {
ds.receive(dp);
// ds.send(new DatagramPacket("aaaa".getBytes(), 4, dp.getAddress(), 11720));
Socket socket = new Socket(dp.getAddress(), 11720); // Cannot make connection!!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to make connection between android server and pc client.
First android send a packet to pc.
I think server can know using this packet, so I use function getAddress().
Then android open socket using port number 11720 and pc try to connect android.
But it cannot connect.
Why this code cannot make connection?
Oh, I just want to know how can I connect from pc to phone.
So I change pc and android code.
Firstly, my goal is connect to android using static port(11720).
But I cannot make connection using static port when using LTE.
So I check socket information using simple program.
This is in pc.
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(11720);
DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);
while (true)
{
ds.receive(dp);
System.out.println(dp.getSocketAddress());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is in android.
new Thread(new Runnable() {
public void run() {
try {
DatagramSocket s = new DatagramSocket(11720);
while(true)
{
s.send(new DatagramPacket("aaa".getBytes(), 3, InetAddress.getByName("143.248.55.131" /* Server address */), 11720));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
I execute programs using WiFi and LTE.
And result is
/143.248.56.118:11720 <- using WiFi
/143.248.56.118:11720
/143.248.56.118:11720
/117.111.7.124:35645 <- change LTE
/117.111.7.124:35645
/117.111.7.124:35645
When using LTE, socket's port number is changed.
so I cannot send packet using static port number.
How can I solve this problem?
Firstly, why are you complicating by using Datagram Socket unnecessarily?
You can simply use TCP without any problems.
Well, your client code(Java PC) might be waiting at:
ds.receive(dp);
And so the socket might not get created.
Although the android program is sending a packet but UDP being unreliable, the packet may not be received by the client code.
Also, this can be due to network issues like both cannot get a connection, or there might be a NAT between them which would not let any UDP packet to let in.
So, I would suggest to simply use TCP. Don't complicate by first sending a UDP packet and then connecting with TCP.

How to reconnect a socket when catch a SocketException in java?

I've met a problem that when I process my data on my program, that the server may getoff its socket of my client program, but i need to catch this exception and reconnect it to run my program. i did not use the serverSocket but all use the Socket to create an object.
I need your help. the implement code in detail is welcome. thanks
You can't. You have to create a new one if you're the client, and just hope the client will do that if you're the server.
try to create new one with same ip and port
while (!socket.isConnected()) {
try {
socket = new Socket(inetAddress, port);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}

Categories

Resources