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.
Related
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();
}
}
}
}
That is my program in java for my android app. I tried to create tcp connection with tcp server. I can connect to server with another applications so that i can send and receive from tcp server. With my code and with my program i can send messages to server very eazy, but i have troubles with receiving messages from server.
private Socket socket;
private final int SERVERPORT = 6060;
private final String SERVER_IP = "192.168.0.8";
public TextView tv;
private PrintWriter out;
private InputStream in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)this.findViewById(R.id.textView1);
new Thread(new ClientThread()).start();
}
Here is my problem i dont know how to receive strings or bytes from server. When i run my app on phone it closes the open window and say that program stop working. If i delete this section of code(public void ONCLICK2) i can transmit messages to server.
public void ONCLICK2(View view) {
try {
in=socket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte array[]=new byte[1];
try {
int i=in.read(array);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So please help me with that section of code. How can i receive string send from TCP server.
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.editText1);
String str = et.getText().toString();
out.println(str);
out.flush();
}catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Simply put, the problem is you are intercepting the byte array of an unknown length and attempting to store them in array the size of one. Furthermore, it is ideal to append the packet size prior to the data in the packet and perhaps create the intercept in a separate thread waiting for incoming packets.
To just fix your ONCLICK2 you should do the following:
byte[] data = new byte[6556];
try {
in = socket.getInputStream();
// NOTE: The data byte array will contain empty values if
// under the size of 6556
int size = in.read(data);
// send to LogCat
Log.e("String", data.toString());
} catch (Exception e) {
e.printStackTrace();
}
I have not tested this code, but this should fix your problem.
I'm trying to connect my Glass with Arduino and a Wifi Shield.
At MenuActivity.java I call (and others methods... but this is the call) :
protected void onCreate(Bundle savedInstanceState)
{
new ConnexioArduino().execute();
super.onCreate(savedInstanceState);
}
And my ConnexioArduino.java :
private boolean socketReady;
private BufferedWriter outA;
private BufferedReader inA;
private Socket mySocket;
....
....
#Override
protected Void doInBackground(Void... params) {
socketReady = true;
String Host = "192.168.43.177";
int Port = 10001;
outA = null;
inA = null;
mySocket = null;
try {
mySocket = new Socket(Host, Port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mySocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So it only does a connexion between Glass-Arduino Wifi Shield through Socket. But when I execute my app it stops and it gives me the following error : (see image on this link, sorry for the URL I don't have the enough reputation)
http://google-glass-api.googlecode.com/issues/attachment?aid=4630000000&name=Captura+de+pantalla+2014-04-09+a+la%28s%29+13.08.12.png&token=CyuXI9n0-00D4I0inCvN122h42g%3A1398618521508&inline=1
Share your manifest, it should have:
<uses-permission android:name="android.permission.INTERNET"/>
If not you will get a socket failed:eacces (permission denied) error if you step-debug.
Another possible problem is that your server is not accepting the socket request for any number of reasons.
I was able to use your exact code, set up a basic node server on a laptop, and open and close the socket without a crash.
Socket code on Glass should be just like Android according to this:
https://code.google.com/p/google-glass-api/issues/detail?id=272
If you continue to have issues log out the value of e in the exceptions you are catching and paste the result into your question.
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();
}
}
}
I have a very similar behaviour as described here:
running on a Mac Book Pro, Snow Leopard
using Multicast Sockets to send and receive packets on localhost
I'm using Eclipse and observed the following behaviour when the client / server are started from within the workspace:
if the wireless interface (airport) is up and running, the client does not receive any packets
if the interface is turned off, everything works as expected
But what I don't understand is:
if I create a JAR and run the code in any console -> all good! Just Eclipse seems not to like airport ;-)
depending on what wireless network I'm connected to, the above behaviour might change, i.e. it also works if airport is enabled (for example # Uni)
Does anyone have an idea 'bout this?
Cheers
Below the straightforward code for server / client:
#Override
public void run() {
String multicastAddress = "224.0.0.2";
int multicastPort = 8000;
MulticastSocket socket = null;
try {
try {
InetAddress multicastGoup = InetAddress.getByName(multicastAddress);
socket = new MulticastSocket(multicastPort);
socket.joinGroup(multicastGoup);
} catch (IOException e) {
e.printStackTrace();
return;
}
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
System.out.println("BEFORE RECEIVE: listening on " + multicastAddress + ":" + multicastPort);
socket.receive(packet);
System.out.println("PACKET RECEIVED");
System.err.println("Client received: " + new String(packet.getData()));
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
Server:
public void run() {
MulticastSocket socket = null;
try {
String multicastAddress = "224.0.0.2";
int multicastPort = 8000;
InetAddress multicastGoup = InetAddress.getByName(multicastAddress );
socket = new MulticastSocket(multicastPort);
socket.joinGroup(multicastGoup);
byte[] data = new String("Teststring").getBytes();
while (true) {
socket.send(new DatagramPacket(data, data.length, multicastGoup, multicastPort));
System.out.println("SERVER: Datagram sent");
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
From Class MulticastSocket:
void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
Joins the specified multicast group at the specified interface.
Try using a specific interface so your joinGroup doesn't fall into the default - which may vary according on available, open ones or due to Eclipse settings.
joinGroup
public void joinGroup(SocketAddress mcastaddr,
NetworkInterface netIf)
throws IOException
Joins the specified multicast group at the specified interface.
If there is a security manager, this method first calls its
checkMulticast method with the mcastaddr argument as its argument.
Parameters:
mcastaddr - is the multicast address to join
netIf - specifies the local interface to receive
multicast datagram packets,
-- here is the catch
or null to defer to the interface set by
setInterface(InetAddress) or
setNetworkInterface(NetworkInterface)