I need to receive data packets send from a GSM modem through GPRS with my android mobile...
Can any one help me how to send and receive..
What protocol has to be used?
Create a Thread in server starts and do the following
ServerSocket serverSocket = new ServerSocket(8000); //8000 - port number
Socket client = serverSocket.accept(); // thread will wait here till a client connects
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(client.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
client.getOutputStream());
while ((inputLine = inFromClient.readLine()) != null) {
System.out.println("Server: " + inputLine);
if(inputLine.equals("END"))
{
outToClient.writeBytes("END\n");
}
else
{
outToClient.writeBytes("Received\n");
}
}
inFromClient.close();
outToClient.close();
Its a TCP connection you need to handle
Related
I am developing an Android multiplayer game using Wi-Fi direct.
Using Wi-Fi direct, I am able to establish connection between peer devices. Also the code is able to send the data from client device to server device. (According to Android documentation, the Wi-Fi direct uses client-server model)
Problem:
I am not able to share the data from server device to client device using Wi-Fi direct.
I have following questions:
Is there any other way to transfer data (bi-directional) between two
Android devices which are connected through Wi-Fi Direct?
During my online research I understood that to send data from server
device to client device, server needs to know the client’s IP
address. How to use this client’s IP address to send data from
server device to client device? (I am able to fetch the client’s IP
address)
I'd appreciate any suggestions on these queries. Thank you in advance.
Code:
Server Side
public class DataTransferAsyncTask extends AsyncTask<Void,Void,String>{
ServerSocket serverSocket;
Socket client;
InputStream inputstream;
Context context = mActivity.getApplicationContext();
String s;
InetAddress client_add;
#Override
protected String doInBackground(Void... voids) {
try{
serverSocket = new ServerSocket(9999);
Log.e("hello", "Server: Socket opened");
client = serverSocket.accept();
Log.e("hello", "Server: connection done");
inputstream = client.getInputStream();
// OutputStream outputStream = serverSocket.getO
//getting data from client
byte[] address = new byte[12];
if(client.isConnected())
inputstream.read(address);
s = new String(address);
String only_add = new String();
only_add = s.substring(0,12);
client_add = InetAddress.getByName(only_add);
Log.e("hello", "Server: clients ip 1 " + only_add);
Log.e("hello", "Server: converted address 1 " + client_add + " \n is connected"+
client.isConnected());
//send data to client
OutputStream stream = client.getOutputStream();
stream.write(s.getBytes());
Log.e("hello","context value "+context);
// cancel(true);
}catch (IOException e){
}
return null;
}
}
Client Side:
#override
protected void onHandleIntent(Intent intent) {
Log.e("hello","client socket");
Toast.makeText(this,"client socket",Toast.LENGTH_LONG).show();
Context context = getApplicationContext();
if(intent.getAction().equals(action_send_data)){
String host = intent.getStringExtra(group_owner_address);
Socket socket = new Socket();
int port = intent.getIntExtra(group_owner_port,9999);
//binding connection
try{
String x="hello";
Log.e("hello","opening client socket");
byte[] address = getLocalAddress();
String ipAdd = getDottedDecimalIP(address);
socket.bind(null);
socket.connect(new InetSocketAddress(host,port),socket_timeout);
Log.e("hello","device socket address "+ socket.getInetAddress() );
Log.e("hello","client socket is connected"+socket.isConnected());
Log.e("hello","device address :"+ipAdd + " byte "+ address);
//sending data to server
OutputStream stream = socket.getOutputStream();
stream.write(ipAdd.getBytes());
//getting data from the server(supposed to)
InputStream inputstream = socket.getInputStream();
byte[] address_to_sto_fr_ser = new byte[15] ;
inputstream.read(address_to_sto_fr_ser);
String s = new String(address_to_sto_fr_ser);
Log.e("msg from server","msg from server "+s);
// stream.close();
// is.close();
}catch (IOException e){
}
}
}
The communication between client and WiFi Direct Group Owner is based on Socket server running on the Group Owner and clients connected to that server.
Once WiFi Direct group is formed(you can know that by checking "onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo)"), check if the current device is the Group Owner and if so, start the sockets server (similar to your code):
mServerSocket = new ServerSocket(mPort);
Log.e(getClass().getSimpleName(), "Running on port: " + mServerSocket.getLocalPort());
Then next, add this line to accept connections and store a reference of the client socket:
Socket mSocket = mServerSocket.accept();
Now, you have a reference of the client socket, you can use it to send data / messages to it. Next, the other device (client) should initiate a connection to the socket server:
mSocket = new Socket();
mSocket.bind(null);
mSocket.connect(new InetSocketAddress(mAddress, mPort), 500);
To send message from server to client:
DataOutputStream mDataOutputStream = new DataOutputStream(mSocket.getOutputStream());
Send simple message:
mDataOutputStream.writeUTF(message);
mDataOutputStream.flush();
Hope this helps.
I'm trying to send some commands to Android (client) from VB.NET (server) using sockets. I can connect the client to the server, but I don't know how to receive the commands sent by the server.
Here's a part of my Android code:
public void connect(View v){ //called on button click
SERVER_IP = ip.getText().toString(); //it gets the server's ip from an editText
SERVER_PORT = Integer.parseInt(port.getText().toString()); //and the port too
Toast.makeText(this, "Trying to connect to\n" + SERVER_IP + ":" + SERVER_PORT + "...", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
public void run() {
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVER_PORT); //It establishes the connection with the server
if(socket != null && socket.isConnected()){ //not sure if it is correct
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Here comes the problem, I don't know what to add...
}
} catch (Exception e) {
}
}
}).start();
}
And here's a part of my VB.NET send code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
send(TextBox1.text)
End Sub
Private Sub Send(ByVal command)
Dim temp() As Byte = UTF8.GetBytes(command) 'Is UTF8 right to use for that?
stream.Write(temp, 0, temp.Length)
stream.Flush()
End Sub
Question1: is it right to us UTF8 instead of for example ASCII encoding?
Question2: what would I change in the Android code if it wanted to use a timer that sends a command every second?
Thanks.
To read input from a BufferedReader you need to do something similiar to this:
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while((line = input.readLine()) != null){
// do something with the input here
}
A nice tutorial on sockets is available from oracle in the docs: http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
The default charset on Android is UTF-8 http://developer.android.com/reference/java/nio/charset/Charset.html, so no worries there but you can always send a byte stream from the server onto the client and decode it however you want.
To receive a byte stream you need to do this:
BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
byte[] buffer = new byte[byteCount];
while(input.read(buffer, 0, byteCount) != -1 ){
// do something with the bytes
// for example decode it to string
String decoded = new String(buffer, Charset.forName("UTF-8"));
// keep in mind this string might not be a complete command it's just a decoded byteCount number of bytes
}
As you see it's much easier if you send strings instead of bytes.
If you want to receive input from the server periodically, one of the solutions would be to create a loop which opens a socket, receives input, process it, closes the socket, and then repeats, our you could just keep the loop running endlessly until some command like "STOP" is received.
I saw many pages, and try many advices, but still can't receive data via UDP on device (nexus 4). I work in my LAN, over wifi (3G is off).
I have a client, on PC (192.168.1.5) and consumer on Android device (192.168.1.3:54445)
Here is a client code:
String string = "hello udp";
DatagramSocket socket = null;
try {
address = InetAddress.getByName("192.168.1.3");
socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 54445);
socket.send(packet);
Here is a consumer code:
DatagramSocket socket = null;
stop = false;
InetAddress address = null;
try {
socket = new DatagramSocket(54445);
while (!stop) {
byte[] buffer = new byte[minBufSize];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Log.d(this.getClass().getSimpleName(), String.valueOf(packet.getLength()));
Debugger stop on socket.receive(packet). Consumer work in AsyncTask.
Thank you!
It's my fault, at first check you router settings.
I'm trying to keep a listening UDP port on 23000, the app works well in local environment.
But switching to 3G there are no chances, traffic is blocked.
I tried 'opening' the carrier channel sending 4bytes of data on the same port before receiving:
InetAddress serverAddr = InetAddress.getByName(SOULISSIP);
DatagramChannel channel = DatagramChannel.open();
socket = channel.socket();
//socket = new DatagramSocket();
socket.setReuseAddress(true);
//InetSocketAddress ia = new InetSocketAddress("localhost", SERVERPORT);
InetSocketAddress sa = new InetSocketAddress(SERVERPORT);
socket.bind(sa);
DatagramPacket holepunh = new DatagramPacket(new byte[]{0,1,2,3},4, serverAddr, SERVERPORT);
socket.send(holepunh);
// create a buffer to copy packet contents into
byte[] buf = new byte[200];
// create a packet to receive
DatagramPacket packet = new DatagramPacket(buf, buf.length);
Log.d("UDP", "***Waiting on packet!");
socket.setSoTimeout((int) opzioni.getDataServiceInterval());
// wait to receive the packet
socket.receive(packet);
UDPSoulissDecoder.decodevNet(packet);
socket.close();
is there a simple way to open the channel and receive UDP datagrams on port 23000?
So, the answer was in the request, while I was struggling with receiving socket. I had to bind the sender socket to the local port used for receiving datagrams:
//send
serverAddr = InetAddress.getByName(SOULISSIP);
DatagramChannel channel = DatagramChannel.open();
sender = channel.socket();
sender.setReuseAddress(true);
//amateur hole punch
InetSocketAddress sa = new InetSocketAddress(SERVERPORT);
sender.bind(sa);
//stuff to send
List<Byte> macaco = new ArrayList<Byte>();
macaco = Arrays.asList(pingpayload);
ArrayList<Byte> buf = buildVNetFrame(macaco, prefs);
//someone help me here...
byte[] merd = new byte[buf.size()];
for (int i = 0; i < buf.size(); i++) {
merd[i] = (byte) buf.get(i);
}
packet = new DatagramPacket(merd, merd.length, serverAddr, SOULISSPORT);
sender.send(packet);
The receiver and the sender are on separate threads, using same local port. .setReuseAddress(true) permitted this.
Im a newbie in this so please escuse me if i ask dumb questions.
Im trying to make a UDP connection between Eclipse's PC Emulator & a android phone
(or between two android phone devices).
I have a router and the phone connects to the internet thru router's wifi network. The PC is on same network also (direct cable router-PC connection). Im trying to send some text data from Server thread to Client thread but nothing is received/sent. :(
The Server java class (RE-EDITED, Server receives msg. from Client):
public class server implements Runnable
{
// the Server's Port
public static final int SERVERPORT = 6000;
// running Server thread.
public void run()
{
Log.d("redwing","server thread started.");
DatagramSocket serverSocket = null;
try
{
// Open Server Port
serverSocket = new DatagramSocket(server.SERVERPORT);
byte[] receiveData = new byte[32];
byte[] sendData = new byte[32];
// loop until "server_finished" becomes False.
while(createserver.server_finished)
{
if(renderer.gGL!=null) // ignore me, just a null pointer checker
{
// waiting for the incoming client's message packet
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
renderer.recv = new String(receivePacket.getData());
Log.d("server","packet received from client, ETA " + timing.getNow() + " " + renderer.recv); // timing getNow - just returns current system minute & second.
// server is replying to the client back with a message.
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
sendData = new String("server msg").getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
renderer.sent = new String(sendData, 0, sendData.length);
Log.d("server","packet sent to client, ETA " + timing.getNow() + " " + renderer.sent); // timing getNow - just returns current system minute & second.
}
}
// close the socket
if(serverSocket!=null) serverSocket.close();
serverSocket = null;
}
catch (Exception e)
{
Log.e("server", "Error", e);
if(serverSocket!=null) serverSocket.close();
serverSocket = null;
}
finally
{
if(serverSocket!=null) serverSocket.close();
serverSocket = null;
}
Log.d("redwing","server thread terminated.");
}
}
and the Client java class (RE-EDITED, Client does not receive msg from Server) :
public class client implements Runnable
{
public static final int CLIENTPORT = 5000;
// running Client thread.
public void run()
{
Log.d("redwing","client thread started.");
DatagramSocket clientSocket = null;
try
{
// getting local address
clientSocket = new DatagramSocket(server.SERVERPORT);
InetAddress IPAddress = InetAddress.getByName("192.168.0.100");
// displaying IP & hostname.
Log.d("client", "IP: " + IPAddress.getHostAddress() + " Name: " + IPAddress.getHostName());
byte[] sendData = new byte[32];
byte[] receiveData = new byte[32];
// Loop until client_finished becomes False.
while(createclient.client_finished)
{
if(renderer.gGL!=null) // ignore me, just a null pointer checker
{
// sending a message to the server
sendData = timing.getNow().getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, client.CLIENTPORT);
clientSocket.send(sendPacket);
renderer.sent = new String(sendData,0,sendData.length);;
Log.d("client","packet sent to server, ETA " + timing.getNow());
// waiting for the server packet message.
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
renderer.recv = new String(receivePacket.getData());
Log.d("client","packet received from server, ETA " + timing.getNow());
}
}
// close the socket
if(clientSocket!=null) clientSocket.close();
clientSocket = null;
}
catch (Exception e)
{
Log.e("client", "Error", e);
if(clientSocket!=null) clientSocket.close();
clientSocket = null;
}
finally
{
if(clientSocket!=null) clientSocket.close();
clientSocket = null;
}
Log.d("redwing","client thread terminated.");
}
}
the Permisions are enabled in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<user-permission android:name="android.permission.NETWORK" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
I'm running the Server on the android PC Emulator, and the Client on my android Phone.
Both Client & Server threads run just fine but ... the problem is that i dont get any data exchanged between them. The client doesn't receive anyting and the server doesnt receive anything. The packets are sent but nothing received .
What im doing wrong ?
Please help me.
Thank you in advance.
After running your emulator, type it in command prompt - "telnet localhost ", then type "redir add udp:5000:6000". Connect client with port number 5000 and open udp server with port number 6000. Then you can receive client message from udp server.
Take a look for details
clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("<pc ip>"); // instead of "localhost"
public static final String SERVERIP = "127.0.0.1"; // 'Within' the emulator!
public static final int SERVERPORT = 6000;
/* Retrieve the ServerName */
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);