I am stucked at a problem when trying to implement a server/client application for Android.
I implemented a server class which I initialize through the constructor first and then I start an async task for running it.
Here is the server class:
public class Server {
RestaurantTables activity;
ServerSocket serverSocket;
String message = "";
Handler updateConversationHandler;
//static final int socketServerPORT = 8080;
static final int socketServerPORT = 0; // 0 = take any free port
public Server(RestaurantTables activity) {
this.activity = activity;
//Thread socketServerThread = new Thread(new SocketServerThread(this.activity.getHandler()));
updateConversationHandler = new Handler();
map = new HashMap();
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SocketConnectAsyncTask atSockConn = new SocketConnectAsyncTask();
atSockConn.execute();
}
public int getPort() {
return serverSocket.getLocalPort();
}
public void closeSocket() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketConnectAsyncTask extends AsyncTask<Void, Void, Void>
{
int count = 0;
Handler mHandler;
Socket socket;
#Override
//public void run() {
protected Void doInBackground(Void... params) {
try {
/*// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
*/
while (true) {
// block the call until connection is created and return
// Socket object
socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ReceiveMessage atRecMsg = new ReceiveMessage(socket, this.mHandler);
atRecMsg.execute();
}
}
class ReceiveMessage extends AsyncTask<Void, Void, Void> {
private Socket clientSocket;
private Handler mHandler;
private BufferedReader input;
public ReceiveMessage(Socket clientSocket, Handler mHandler)
{
this.clientSocket = clientSocket;
this.mHandler = mHandler;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
while(true) {
try {
String read = input.readLine();// blocking
Message msg = Message.obtain();
msg.obj = read; // Put the string into Message, into "obj" field.
msg.setTarget(mHandler); // Set the Handle
System.out.println("Here is what I read: " + read);
//updateConversationHandler.post(new updateUIThread(read));
//mHandler.sendMessage();
msg.sendToTarget(); //Send the message
try {
OutputStream outputStream = clientSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print("OK");
printStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
//return null;
}
}
public String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress
.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip = inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
The call of the server class looks like:
myServer = new Server (this); // this = activity
So I think the server is running then. After trying to connect from the client with following call...
Client myClient = new Client(sServerIpAddress, sServerPort, Commands.this);
... I get the following exception:
W/System.err: java.net.ConnectException: failed to connect to /192.168.200.2 (port 47803) from /:: (port 48982): connect failed: ECONNREFUSED (Connection refused)
W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:138)
W/System.err: at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:129)
W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:356)
W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
W/System.err: at java.net.Socket.connect(Socket.java:616)
W/System.err: at java.net.Socket.connect(Socket.java:565)
W/System.err: at java.net.Socket.<init>(Socket.java:445)
W/System.err: at java.net.Socket.<init>(Socket.java:248)
W/System.err: at emu.apps.com.jollybell.Client.doInBackground(Client.java:45)
W/System.err: at emu.apps.com.jollybell.Client.doInBackground(Client.java:20)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err: at java.lang.Thread.run(Thread.java:764)
W/System.err: Caused by: android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
W/System.err: at libcore.io.Linux.connect(Native Method)
W/System.err: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:126)
W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:152)
W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:130)
W/System.err: ... 17 more
Honestly I have no clue what is going wrong, even after searching for hours in all possible forums.
If it helps, here is the client class:
class Client extends AsyncTask<String, Void, String> {
public interface ServerResponse {
void serverResultReceived(String output);
}
String sIpAddress, sPort, response;
private Socket socket;
private PrintWriter out;
public ServerResponse delegate = null;
public Client(String sIpAddress, String sPort, ServerResponse delegate)
{
this.sIpAddress = sIpAddress;
this.sPort = sPort;
this.delegate = delegate;
}
//#Override
//public void run() {
#Override
protected String doInBackground(String... params) {
try {
InetAddress serverAddr = InetAddress.getByName(this.sIpAddress);
socket = new Socket(serverAddr, Integer.parseInt(this.sPort));
// First send command
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print(params[0]);
// ... then wait for answer
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice: inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
delegate.serverResultReceived(result);
}
}
So folks. Been some time ago, but I found out how to resolve my problem.
First of all, in the client there is a small problem. I am writing with "out.print" function and then waiting in the server with function "readLine()".
readLine expects the end of a line so either the string should be send with a final "/n" or function "println" has to be used instead of print.
Second, When I started 2 android devices, they could not communicate to each other. I still did not find out why, but using the same device to run the server and the client application worked for me.
Related
java.io.IOException: bt socket closed, read return: -1
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:434)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.InputStreamReader.read(InputStreamReader.java:231)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at java.io.BufferedReader.readLine(BufferedReader.java:397)
08-14 20:30:11.519 30608-1676/com.example.lg.scoreboardapp W/System.err: at com.example.lg.scoreboardapp.MainActivity$ConnectThread.run(MainActivity.java:336)
Sometimes in my app, client unexpectedly closed.
I don't know why......
I have three diveces. one devices is server. others are client.
They are connected well, but one client was closed. other client is still open.
Please give me the solution...!!
It's MainActivitity.. 336Lineenter code here
while(socket != null){
i++;
Log.d("MAinActivity","-----------------"+i+"-----------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str1 = in.readLine(); //<<---Line 336
Log.d("MainActivity","--------------------------------------"+str1+i);
json1 = str1;
parse();
}
It's ConnectThread client
private class ConnectThread extends Thread {
private BluetoothSocket socket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(MainActivity.this, "연결에 실패하였습니다.\n다시 시도하여 주세요", Toast.LENGTH_SHORT).show();
e.printStackTrace();
//mkmsg("Client connection failed: "+e.getMessage().toString()+"\n");
}
socket = tmp;
}
public void run() {
// mkmsg("Client running\n");
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
//mkmsg("Connect failed\n");
e.printStackTrace();
try {
socket.close();
socket = null;
} catch (IOException e2) {
//mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
socket = null;
e2.printStackTrace();
}
// Start the service over to restart listening mode
}
// If a connection was accepted
if (socket != null) {
//mkmsg("Connection made\n");
//mkmsg("Remote device address: "+socket.getRemoteDevice().getAddress().toString()+"\n");
//Note this is copied from the TCPdemo code.
try {
int i=0;
while(socket != null){
i++;
Log.d("MAinActivity","-----------------"+i+"-----------------------------");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final String str1 = in.readLine();
Log.d("MainActivity","--------------------------------------"+str1+i);
json1 = str1;
parse();
}
Log.d("MainActivity_341Line","socket is null.......... check this");
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"MainActivity_341Line socket is null.......... check this",Toast.LENGTH_LONG);
}
});
} catch(Exception e) {
//mkmsg("Error happened sending/receiving\n");
e.printStackTrace();
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Error happened sending/receiving\\n",Toast.LENGTH_LONG);
Log.d("MainActivity_341Line","Error happened sending/receiving");
}
});
try {
socket.close();
socket = null;
} catch (IOException e2) {
//mkmsg("unable to close() socket during connection failure: "+e2.getMessage().toString()+"\n");
socket = null;
Log.d("MainActivity_341Line","Error happened "+e2);
e2.printStackTrace();
}
}
} else {
//mkmsg("Made connection, but socket is null\n");
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Made connection, but socket is null\\n",Toast.LENGTH_LONG);
}
});
}
}
public void cancel() {
try {
socket.close();
Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "채점기기와의 연결이 끝났습니다", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
Try to replace your run() method in your ConnectThread to this:
public void run()
{
Log.e(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
mAdapter.cancelDiscovery();
try
{
mmSocket.connect();
}
catch (IOException e)
{
try
{
Log.e(TAG,"Trying fallback...");
mmSocket = (BluetoothSocket)
mmDevice.getClass()
.getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice, 2);
mmSocket.connect();
Log.e(TAG,"Connected");
}
catch (Exception e2)
{
Log.e(TAG, "Couldn't establish Bluetooth connection!");
try
{
mmSocket.close();
}
catch (IOException e3)
{
Log.e(TAG, "unable to close() " + " socket during connection failure", e3);
}
connectionFailed();
return;
}
}
synchronized (BluetoothHelper.this)
{
mConnectThread = null;
}
connected(mmSocket, mmDevice);
}
I cant create a simple TCP connection to my server.
I created a AsyncTask to send messages, but it didn't work.
I added INTERNET and ACCESS_NETWORK_STATE to the permissions.
I don't know what else to try.
public class ServerCommunicator extends AsyncTask<String,Void,Void>{
public static String SERVER_IP = "192.168.2.148";
public static int SERVER_PORT = 1337;
public static String SERVER_PW = "adsfadsf";
public Context context;
#Override
protected Void doInBackground(String... params) {
//Create Command
CommandFactory cmdFactory = new CommandFactory();
Command cmd = cmdFactory.createCommand();
System.out.println("Cmd created..");
//-----
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = Crypter.Encrypt(cmd.toString(), SERVER_PW);
sendMsgAsByteArr(socket, msg2Send);
Command recCmd = cmdFactory.extractCommandFromStr(receiveMsg(socket));
socket.close();
Toast.makeText(context, recCmd.id, Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void sendMsgAsByteArr(Socket socket, String msg) {
try {
socket.getOutputStream().write(msg.getBytes());
System.out.println("sent cmd..");
} catch (IOException e) {
e.printStackTrace();
}
}
private static String receiveMsg(Socket socket) {
String msg = "";
int c;
ArrayList<Byte> incoming = new ArrayList<Byte>();
try {
while((c = socket.getInputStream().read())!=-1) {
incoming.add((byte)c);
}
byte[] allBytes = new byte[incoming.size()];
for(int i = 0; i < incoming.size(); i++) {
allBytes[i] = incoming.get(i);
}
msg = new String(allBytes);
} catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
My program runs till Socket socket = new Socket(serverAddr, SERVER_PORT); then it stops. It doesn't show any stack trace or errors.
Any ideas?
I debugged your code, and while there were multiple issues, none were related to Android 6.
I created a simplified version of your code and got it working.
One issue is that your context reference was null, so I set it in the constructor.
Another issue is that you were trying to show a Toast on a background thread, which won't work.
Another issue was your send and receive methods, they didn't work for me.
Here's the simplified code that I got working with a TCP/IP server, tested on both Android 4.4.4 and Android 6.
You can take this and expand on it as needed:
public class ServerCommunicator extends AsyncTask<String,Void,String> {
public static String SERVER_IP = "11.222.33.444";
public static int SERVER_PORT = 1234;
public Context context;
public ServerCommunicator(Context c) {
this.context = c;
}
#Override
protected String doInBackground(String... params) {
try {
System.out.println(SERVER_IP);
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
System.out.println("Created serverAddr "+ SERVER_IP);
Socket socket = new Socket(serverAddr,SERVER_PORT);
System.out.println("Socket created..");
//sends the message to the server
PrintWriter mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
String msg2Send = "{\"HelloWorld\", \"1234\"}";
mBufferOut.println(msg2Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String result = in.readLine();
System.out.println("result: " + result);
socket.close();
return result;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
I'm making an Android App to communicate with a computer windows.
I found that it must be easy to do that by forwarding the port with ADB commands.
So i try to make a client/server connection over USB but i have some problems
my server on Windows:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("EchoClient.main()");
Socket client = null;
// initialize server socket
try {
server = new ServerSocket(38300);
server.setSoTimeout(TIMEOUT * 1000);
// attempt to accept a connection
client = server.accept();
Globals.socketOut = new PrintStream(client.getOutputStream());
Globals.socketIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
// Globals.socketIn.YY
} catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus = "Connection has timed out! Please try again";
System.out.println(connectionStatus);
} catch (IOException e) {
System.out.println("error"+ e);
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
System.out.println("Cannot close server socket"+ ec);
}
}
if (client != null) {
System.out.println("connected");
}
}
public static class Globals {
private static String typeOfTransmission ;
static PrintStream socketOut = null;
static BufferedReader socketIn = null;
public static synchronized String getTypeTransmission(){
return typeOfTransmission;
}
public static synchronized void setTypeTransmission(String s){
typeOfTransmission = s;
}
}
}
android APP client
private Runnable initializeConnection = new Thread() {
public void run() {
Socket client = null;
// initialize server socket
try {
Log.d("ip",getLocalIpAddress());
client = new Socket(getLocalIpAddress(), 38300);
Globals.socketIn = new Scanner(new InputStreamReader(
client.getInputStream()));
Globals.socketOut = new PrintWriter(client.getOutputStream());
// Globals.socketIn.YY
} catch (SocketTimeoutException e) {
// print out TIMEOUT
connectionStatus = "Connection has timed out! Please try again";
mHandler.post(showConnectionStatus);
} catch (IOException e) {
Log.e(TAG, "" + e);
} finally {
// close the server socket
try {
if (server != null)
server.close();
} catch (IOException ec) {
Log.e(TAG, "Cannot close server socket"+ ec);
}
}
if (client != null) {
Globals.connected = true;
// print out success
connectionStatus = "Connection was succesful!";
Log.d(TAG, "connected!");
mHandler.post(showConnectionStatus);
while (Globals.socketIn.hasNext()) {
socketData = Globals.socketIn.next();
mHandler.post(socketStatus);
}
}
}
};
public String getLocalIpAddress(){
try{
for(Enumeration<NetworkInterface> en =NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){
NetworkInterface intf = en.nextElement();
for(Enumeration<InetAddress> enumIpAddress= intf.getInetAddresses();enumIpAddress.hasMoreElements();){
InetAddress inetAddress = enumIpAddress.nextElement();
if (!inetAddress.isLoopbackAddress()){
return inetAddress.getHostAddress().toString();
}
}
}
}catch(SocketException ex){
Log.e("ServerActivity",ex.toString());
}
return null;
}
Logger
01-29 11:43:49.640: D/ip(2981): fe80::a806:ff:fec6:d3d%p2p0
01-29 11:43:49.650: E/Connection(2981): java.net.ConnectException: failed to connect to /fe80::a806:ff:fec6:d3d%p2p0%4 (port 38300): connect failed: ECONNREFUSED (Connection refused)
thank you
float totalKm = Contsants.jobEndKm-Contsants.jobStartKm ;
jcTotalKms.setText(String.format("%.2f",totalKm));
//jcTotalKms.setText(Float.toString((float) (totalKm/16.0)));
//finding total fare here
//int value=100;
if (totalKm<Contsants.minDist)
{
jcWaitingFare.setText("0");
float totalfare=Contsants.minFare;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
else
{
jcWaitingFare.setText(Integer.toString((Contsants.cont_WaitingTimeInSec/60)*1));
float totalfare= Contsants.minFare+ ((totalKm-Contsants.minDist) *Contsants.rupeeKm) +(Contsants.cont_WaitingTimeInSec/60)*1;
jcTotalFare.setText(String.format("%.2f",(totalfare)));
Contsants.jobTotalKm= totalKm;
Contsants.jobTotalFare=totalfare;
}
tcpsocket class
public class tcpSocket extends Thread{
static boolean startSocket=false;
public static final String SERVERIP = "ip address here"; //your computer IP address
public static final int SERVERPORT = 8900;
private static boolean mRun = false;
public static Socket socket;
public static OnMessageReceived mMessageListener;
public static OnMessageReceived getmMessageListener() {
return mMessageListener;
}
public static void setmMessageListener(OnMessageReceived mMessageListener) {
tcpSocket.mMessageListener = mMessageListener;
}
public tcpSocket()
{
}
#Override
public void run(){
//some long operation
startSocket=true;
while(startSocket)
{
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.d("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
Log.d("TCP Client", "C: Sent.");
Log.d("TCP Client", "C: Done.");
final OutputStream out =socket.getOutputStream();
writeResponse(out, "$0001~01~"+Contsants.Cont_IMEINo+"~Version#");
//in this while the client listens for the messages sent by the server
final InputStream in = socket.getInputStream();
while(!mRun)
{
if (!(in.available() > 0)) {
goSleep(2000);
continue;
}
processClient(in);
}
}catch (Exception e) {
// TODO: handle exception
}finally{
socket.close();
}
} catch (Exception e) {
Log.d("tcp error",e.toString());
// TODO: handle exception
}
}
}
private void goSleep(final long milliSec) {
try {
Thread.sleep(milliSec);
} catch (final InterruptedException e) {
Log.e("server conn Thread ","Sleeping client interrupted" + e);
}
}
private void processClient(final InputStream in) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
final char[] cbuf = new char[1024];
final int length = reader.read(cbuf);
if (length <= 0) {
Log.d("d","No data read from client.");
return;
}
cbuf[length] = '#';
String packet = new String(cbuf, 0, length + 1);
if (!packet.startsWith("$") && !packet.contains("#")) {
Log.d("d","Invalid packet recieved: " + packet);
return;
}
try
{
if(!packet.contains("$0002") && !packet.contains("$0423"))
{
final String [] packetDo=packet.split("\\~");
writeResponse(socket.getOutputStream(), "$102~"+packetDo[1]+"~"+Contsants.Cont_IMEINo+"#");
}
Log.d("d","Recived packet is :"+packet);
Message msg = new Message();
Bundle b = new Bundle();
b.putString("ServerMsg", packet);
msg.setData(b);
// send message to the handler with the current message handler
mHandler.sendMessage(msg);
}catch (Exception e) {
// TODO: handle exception
Log.e("TCP", "p: Error", e);
}
}
Handler mHandler =new Handler(){
#Override
public void handleMessage(Message message){
//update UI
Bundle b = message.getData();
final String data =b.getString("ServerMsg");
mMessageListener.messageReceived(data);
}
};
/*public class MyAsync extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
String response = null;
return SendMessage(response);
}
}
public static boolean SendMessage(final String response) {
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out, response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun = true;
return false;
}
return true;
}
*/
public static boolean SendMessage(final String response)
{
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out,response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun=true;
return false;
}
return true;
}
private static void writeResponse(final OutputStream out, final String response) throws IOException {
// logger.info("Sending response to client: " + response);
out.write(response.getBytes());
out.flush();
}
}
here is my code for calculating distance and fare together when the condition exceeds minimum(minDist) kilometer. But while checking this application in real device it hangs up after two kilometer. Because after two kilometer it goes to else condition part. i don't know how to solve this issue.
I want to send a file from client to Server by using Socket Programming.
I unable to transfer this file, client side is giving message OK, server get freeze at serverClient.accept,and only dispalys Listening on
Ip: 10.81.81.125, I am so confused, Kindly help.
Thanks in advance.
Client Code:
public class uploadData extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
} catch (Exception e) {
}
}
#Override
protected String doInBackground(String... arg0) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, Constants.SERVERPORT);
socket.setSoTimeout(90000);
connected = true;
if (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
try {
// where you issue the commands
File sFile = new File(filePath);
BufferedInputStream buffIn = null;
buffIn = new BufferedInputStream(
new FileInputStream(sFile));
out.print(buffIn);
} catch (Exception e) {
// TODO: handle exception
}
// setText();
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(SynServer.this,getString(R.string.noServer), Toast.LENGTH_SHORT).show();
connected = false;
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
// TODO Auto-generated method stub
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
#Override
protected void onDestroy() {
Runtime.getRuntime().gc();
super.onDestroy();
}
}
Server Code:
public class Socket_File_ServerActivity extends Activity {
private TextView serverStatus;
// default ip
public static String SERVERIP = "10.0.2.15";
// designate a port
public static final int SERVERPORT =12345;
private Handler handler = new Handler();
private ServerSocket serverSocket;
Socket client=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
//
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
Looper.prepare();
if (SERVERIP != null) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
}
});
Toast.makeText(getApplicationContext(), serverSocket.getLocalSocketAddress().toString()
, Toast.LENGTH_LONG).show();
serverStatus.append("\n"+serverSocket.getLocalSocketAddress().toString());
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
final String myline=new String(line);
handler.post(new Runnable() {
public void run() {
// tv_chatbox.setText("Client said:="+myline);
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
serverStatus.setText("Error"+e.getMessage());
}
});
e.printStackTrace();
}
}
}
// gets the ip address of your phone's network
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
public class TCPServer {
//tcp port on local host port
public static final int PORT = 3100;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
//server socket, can also specify Host Address
serverSocket = new ServerSocket(PORT);
//start listening on port
System.out.println("Listening for clients on port: " + PORT);
} catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.err.println(e.getMessage());
System.exit(-1);
}
//create new thread pool
ThreadPool threadPool = new ThreadPool(2);
//call runnable method on thread pool
threadPool.runTask(startServer(serverSocket));
//join thread pool
threadPool.join();
//close server socket and destroy threadpool
serverSocket.close();
threadPool.destroy();
}
private static Runnable startServer(final ServerSocket socket) {
return new Runnable() {
#Override
public void run() {
//keep looping and looking for data
while (true)
try {
//create new thread
new TCPServerThread(socket.accept()).start();
} catch (IOException e) {
System.out.println("Client got disconnected!" + "\nListening for clients on port: " + PORT);
}
}
};
}
}
Server
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class TCPServerThread extends Thread {
private Socket socket = null;
//constructor
public TCPServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
//read data into buffered stream
BufferedInputStream stream = new BufferedInputStream(
socket.getInputStream());
//create music player object with buffered stream
Player p = new Player(stream);
//start playing
p.play();
//close socket after done playing
socket.close();
} catch (IOException e) {
System.out.println("Client got disconnected!" + "\nListening for clients on port: " + TCPServer.PORT);
} catch (JavaLayerException e) {
System.out.println("Client got disconnected!" + "\nListening for clients on port: " + TCPServer.PORT);
}
}
}
Thread Pool
import java.util.LinkedList;
class ThreadPool extends ThreadGroup {
private boolean isAlive;
private LinkedList<Runnable> taskQueue;
private int threadID;
private static int threadPoolID;
//constructor
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
// Changes the daemon status of this thread group.
setDaemon(true);
isAlive = true;
taskQueue = new LinkedList<Runnable>();
for (int i = 0; i < numThreads; i++) {
new PooledThread().start();
}
}
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask() throws InterruptedException {
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable) taskQueue.removeFirst();
}
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
interrupt();
}
}
public void join() {
// notify all waiting threads that this ThreadPool is no
// longer alive
synchronized (this) {
isAlive = false;
notifyAll();
}
// wait for all threads to finish
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i = 0; i < count; i++) {
try {
threads[i].join();
} catch (InterruptedException ex) {
}
}
}
private class PooledThread extends Thread {
public PooledThread() {
super(ThreadPool.this, "PooledThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
} catch (InterruptedException ex) {
}
// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}
// run the task, and eat any exceptions it throws
try {
task.run();
} catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}