I am trying to create a very-very simple server-client application in Android.
The server is running on my pc, it was written in python. (just a simple while (true) loop which receives a string and responses with an other string.)
The problem is in the Android client. So i tried to create a singleton class in a separate thread, which:
create the socket
connect to the socket
is reachable from other activites
write to socket
read from socket
I try to write and read from an other asynctask.
It is working until i try to write to the socket again. (1 write is ok, any other attempts are failed.) I do not get any exception, i checked if the socket closed or the writer null, etc. The message just not wrote to the socket.
What's wrong with this solution? :/
Could you please help me?
Here is the thread:
public class ConnectThread extends Thread
{
// singleton Part
private static class ThreadHolder {
static final ConnectThread instance = new ConnectThread();
}
public static synchronized ConnectThread getInstance(){
if(ThreadHolder.instance == null)
Log.d("mytag", "NEW INSTANCE CREATED");
// return (ThreadHolder.instance == null) ? ThreadHolder.instance = new ConnectThread() : ThreadHolder.instance;
return ThreadHolder.instance;
}
private ConnectThread(){
}
// implementation part
private Socket mSocket;
private BufferedWriter socketWriter;
private BufferedReader socketReader;
public Socket getSocket() {
return mSocket;
}
public void WriteToSocket(String msg)
{
try{
if(!(mSocket.isClosed()))
{
Log.d("mytag", "Writing to socket");
if(socketWriter == null)
Log.d("mytag", "Writer closed - in write to socket");
socketWriter.write(msg);
socketWriter.flush();
}else
Log.d("mytag", "CANT write to socket");
}catch(IOException e)
{
e.printStackTrace();
Log.d("mytag", e.toString());
}
}
public String ReadFromSocket()
{
try
{
if(!(mSocket.isClosed())) {
Log.d("mytag", "Reading from socket");
if(socketReader == null)
{
Log.d("mytag", "Reader closed - in read from socket");
}
return socketReader.readLine();
}else
{
Log.d("mytag", "CANT from socket");
return null;
}
}catch (IOException e)
{
e.printStackTrace();
return null;
}
}
#Override
public void run() {
try
{
mSocket = new Socket();
mSocket.setKeepAlive(true);
try
{
mSocket.setTcpNoDelay(true);
}
catch (SocketException e)
{
}
mSocket.connect(new InetSocketAddress("192.168.0.128", 8888), 2000);
if(!(mSocket.isClosed()))
{
Log.d("mytag", "SOCKET IS RUNNING");
socketWriter = new BufferedWriter(new OutputStreamWriter(this.mSocket.getOutputStream()));
socketReader = new BufferedReader(new InputStreamReader(this.mSocket.getInputStream()));
if(socketWriter == null)
{
Log.d("mytag", "WRITER NOT CREATED");
}else
Log.d("mytag", "WRITER READY");
if(socketReader == null)
{
Log.d("mytag", "READER NOT CREATED");
}else
Log.d("mytag", "READER READY");
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
And here are the attempts to read, write:
#Override
protected Void doInBackground(Void... params)
{
PrintDebugMsg("do in background");
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Checking network availability...");
//progressDialog.setTitle("Checking network availability...");
//check network:
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(parentContext.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected())
{
networkAvail = true;
response += "| Network available |";
}
PrintDebugMsg("do in background 2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeStatusImg(imgvNetworkStatus, networkAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Pinging server");
//progressDialog.setTitle("Pinging server...");
//check server status
try {
PrintDebugMsg("do in background 3");
if(!(ConnectThread.getInstance().getSocket().isClosed()))
{
ConnectThread.getInstance().WriteToSocket(PING_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
if(line.equals(PING_ACK))
{
serverAvail = true;
response += " | pinged |";
PrintDebugMsg("do in background 4", true);
}
}
else{
response += " | NOT pinged |";
PrintDebugMsg("do in background 5", true);
throw new UnknownHostException();
}
PrintDebugMsg("do in background 6", true);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during server check |";
PrintDebugMsg("do in background 7", true);
} finally{
PrintDebugMsg("do in background 9", true);
if(ConnectThread.getInstance().getSocket() != null){
}
}
PrintDebugMsg("do in background 10", true);
if(serverAvail)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvServerStatus, serverAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Connectiong to server...");
//connect to server:
try {
PrintDebugMsg("do in background 11",true);
//socket = new Socket(dstAddress, dstPort);
//socket = ConnectThread.getInstance().getSocket();
PrintDebugMsg("do in background 12",true);
if(!(ConnectThread.getInstance().getSocket().isClosed())) {
PrintDebugMsg("do in background 13",true);
PrintDebugMsg("do in background 14",true);
PrintDebugMsg("do in background 15",true);
ConnectThread.getInstance().WriteToSocket(CONN_REQ_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
PrintDebugMsg("conn line = " + line, true);
if(line != null && line.equals(CONN_ACK))
{
connected = true;
response += "| connected |";
PrintDebugMsg("do in background 12");
}
}else
{
response += "| NOT connected |";
PrintDebugMsg("do in background 13");
throw new UnknownHostException();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during connecting |";
}finally{
PrintDebugMsg("connection finished");
}
if(connected) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvConnectionStatus, connected?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------
------------
return null;
}
The "util" functions:
private void PrintDebugMsg(String msg, boolean b)
{
if(b)
Log.d("mytag", msg);
}
private void changeProgressMsg(final ProgressDialog dialog,final String value){
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.setMessage(value);
}
});
}
private void changeStatusImg(final ImageView imgView, final int imgId){
runOnUiThread(new Runnable() {
#Override
public void run() {
imgView.setImageResource(imgId);
}
});
}
Sever.java
public class Server {
public static void main(String[] args) {
new Server().startServer();
}
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10);
Runnable serverTask = new Runnable() {
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Waiting for clients to connect...");
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
} catch (IOException e) {
System.err.println("Unable to process client request");
e.printStackTrace();
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private final Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
System.out.println("Got a client !");
// Do whatever required to process the client's request
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
i Use Socket To communicate between android and wifi its return me OutOfMemory Error When i Trying to disconnect 3 seconds after Sending Data
i have an interface to handle data:
public interface SocketConnections {
public void onSocketConnectionChanged(boolean isConnected, Socket socket);
public void onMessageRecieved(String Message);
public void onMessageSent();
}
SocketClass
public class connectSocket implements Runnable {
public Socket socket;
private DataOutputStream out;
private InputStream in;
private SocketConnections connections;
private static final String TAG = "connectSocket";
public connectSocket(SocketConnections connections) {
this.connections = connections;
}
#Override
public void run() {
connect();
}
private void connect() {
disconnect();
try {
try {
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
socket = new Socket(wsConfig.HOST_ADDRESS, wsConfig.PORT_NUMBER);
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
if (socket.isConnected()) {
connections.onSocketConnectionChanged(true, socket);
Log.i(TAG, "Connected");
while (socket.isConnected()) {
out = new DataOutputStream(socket.getOutputStream());
in = socket.getInputStream();
String S;
if (in != null) {
while (true) {
byte[] content = new byte[1024];
try {
Thread.sleep(2000);
int bytesRead = in.read(content);
if (bytesRead == -1) {
break;
}
byte[] x = Arrays.copyOfRange(content, 0, bytesRead);
Log.i(TAG, "run: " + x.length);
S = Util.fromByteArrayToHexString(x);
connections.onMessageRecieved(S);
} catch (Exception e) {
}
}
}
}
}
} catch (Exception e) {
connections.onSocketConnectionChanged(false, socket);
e.printStackTrace();
}
}
}).start();
} catch (Exception ignored) {
}
} catch (Exception ignored) {
}
}
public void sendData(final byte[] S) {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
out.write(S);
out.flush();
connections.onMessageSent();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
public void disconnect() {
if (socket != null && socket.isConnected()) {
try {
socket.close();
connections.onSocketConnectionChanged(false, socket);
// Toast.makeText(G.context, "سیستم به سرور متصل نیست.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i want to add 3 seconds delay after sending data and Disconnect
like this
public void sendData(final byte[] S) {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
out.write(S);
out.flush();
connections.onMessageSent();
Thread.sleep(3000);
disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
its return me out of memory error and force close what should i do?
ok so i found my problem and solved it. i'm not sure but i think when i'm trying to sleep thread inside other thread its some how its going to stop itself before start or i don't know whats happens there but when i put sleep in other method and call that in my first thread its works fine. if some one know about it tell us
Sorry for my english. I am trying to create client and server. Now, my logic is like this:
I start app -> start server -> server listening to all messages -> if client sends message to server -> message goes to server -> message received by server -> server needs to send a message to all its customers.
But the server does not do this
** the server needs to send a message to all its customers**
or maybe
the client is not listening to the server.
my question: Why does the client not accept messages from the server?
//Main
//send message
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sendText.getText().toString().equals("")) {
return;
}
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg(sendText.getText().toString() + "\n");
}
});
//method create server and client, cliend connect to server
createServer(port);
}
public void createServer(int port) {
//create server
ChatServerThread chatServerThread = new ChatServerThread(port);
chatServerThread.start();
//subscribe to server 192.168.31.101 - ip server
createClient("Testov", "192.168.31.101", port);
}
//method for create client
public void createClient(String name, String ipAdress, int SocketServerPORT) {
chatClientThread = new ChatClientThread(
name, ipAdress, SocketServerPORT);
chatClientThread.start();
}
//this is server class
private class ChatServerThread extends Thread {
int SocketServerPORT;
public ChatServerThread(int SocketServerPORT) {
//set port
this.SocketServerPORT = SocketServerPORT;
}
#Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
//create server socket
serverSocket = new ServerSocket(SocketServerPORT);
//waite connect
socket = serverSocket.accept();
Log.e("connect", "server side");
//for input and output
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//listener
while(true) {
if (dataInputStream.available() > 0) {
//read line
String newMsg = dataInputStream.readUTF();
//send line to client
dataOutputStream.writeUTF(newMsg);
final String ms = newMsg;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
//end thread
dataOutputStream.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//this is client side
private class ChatClientThread extends Thread {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
String msgLog = "";
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
//set ip adress and port
socket = new Socket(dstAddress, dstPort);
//for get and post data
String mesageFromServer = null;
dataInputStream = new DataInputStream(socket.getInputStream());
while(!goOut) {
//wait message from server
mesageFromServer = dataInputStream.readUTF();
//output
Log.e("client", mesageFromServer);
final String ms = mesageFromServer;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
msgToSend = "";
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void sendMsg(String msg){
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
private void disconnect(){
goOut = true;
}
}
I implemented the following BluetoothService, it is from the official
Android BluetoothChatService example:
public class BluetoothService extends Thread {
private static final String TAG = BluetoothService.class.getSimpleName();
private static final String NAME_SECURE = TAG + "Secure";
private static final String NAME_INSECURE = TAG + "Insecure";
private static final UUID MY_UUID_SECURE = UUID.fromString("a6fb84f6-20b3-477f-9160-bcd028bddc99");
private static final UUID MY_UUID_INSECURE = UUID.fromString("7dd8441a-1d4b-42f1-9996-a7d507548dfc");
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
private BluetoothAdapter bluetoothAdapter = null;
private Handler handler = null;
private AcceptThread secureAcceptThread = null;
private AcceptThread insecureAcceptThread = null;
private ConnectThread connectThread = null;
private ConnectedThread connectedThread = null;
private int bluetoothState = STATE_NONE;
public BluetoothService(Handler handler) {
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
this.bluetoothState = STATE_NONE;
this.handler = handler;
}
public synchronized void startConnection() {
Log.d(TAG, "start");
if (this.connectThread != null) {
this.connectThread.cancel();
this.connectThread = null;
}
if (this.connectedThread != null) {
this.connectedThread.cancel();
this.connectedThread = null;
}
this.setBluetoothState(STATE_LISTEN);
if (this.secureAcceptThread == null) {
this.secureAcceptThread = new AcceptThread(true);
this.secureAcceptThread.start();
}
if (this.insecureAcceptThread == null) {
this.insecureAcceptThread = new AcceptThread(false);
this.insecureAcceptThread.start();
}
}
public synchronized void connect(BluetoothDevice device, boolean secure) {
if (this.bluetoothState == STATE_CONNECTING) {
if (this.connectThread != null) {
this.connectThread.cancel();
this.connectThread = null;
}
}
if (this.connectedThread != null) {
this.connectedThread.cancel();
this.connectedThread = null;
}
this.connectThread = new ConnectThread(device, secure);
this.connectThread.start();
this.setBluetoothState(STATE_CONNECTING);
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) {
if (this.connectThread != null) {
this.connectThread.cancel();
this.connectThread = null;
}
if (this.connectedThread != null) {
this.connectedThread.cancel();
this.connectedThread = null;
}
if (this.secureAcceptThread != null) {
this.secureAcceptThread.cancel();
this.secureAcceptThread = null;
}
if (this.insecureAcceptThread != null) {
this.insecureAcceptThread.cancel();
this.insecureAcceptThread = null;
}
this.connectedThread = new ConnectedThread(socket, socketType);
this.connectedThread.start();
Message msg = this.handler.obtainMessage(Globals.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Globals.DEVICE_NAME, device.getName());
msg.setData(bundle);
this.handler.sendMessage(msg);
this.setBluetoothState(STATE_CONNECTED);
}
public synchronized void stopConnection() {
if (this.connectThread != null) {
this.connectThread.cancel();
this.connectThread = null;
}
if (this.connectedThread != null) {
this.connectedThread.cancel();
this.connectedThread = null;
}
if (this.secureAcceptThread != null) {
this.secureAcceptThread.cancel();
this.secureAcceptThread = null;
}
if (this.insecureAcceptThread != null) {
this.insecureAcceptThread.cancel();
this.insecureAcceptThread = null;
}
this.setBluetoothState(STATE_NONE);
}
public void write(byte[] out) {
ConnectedThread connectedThread = null;
synchronized (this) {
if (this.bluetoothState != STATE_CONNECTED) {
return;
}
connectedThread = this.connectedThread;
}
connectedThread.write(out);
}
private void connectionFailed() {
Message msg = this.handler.obtainMessage(Globals.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Globals.TOAST, "Unable to connect device");
msg.setData(bundle);
this.handler.sendMessage(msg);
BluetoothService.this.start();
}
private void connectionLost() {
Message msg = this.handler.obtainMessage(Globals.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Globals.TOAST, "Device connection was lost");
msg.setData(bundle);
this.handler.sendMessage(msg);
BluetoothService.this.start();
}
public synchronized int getBluetoothState() {
return this.bluetoothState;
}
private synchronized void setBluetoothState(int bluetoothState) {
this.bluetoothState = bluetoothState;
}
private class AcceptThread extends Thread {
private BluetoothServerSocket serverSocket = null;
private String socketType = null;
public AcceptThread(boolean secure) {
BluetoothServerSocket tempServerSocket = null;
this.socketType = secure ? "Secure" : "Insecure";
try {
if (secure) {
tempServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE);
} else {
tempServerSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + socketType + "listen() failed", e);
}
this.serverSocket = tempServerSocket;
}
public void run() {
this.setName("AcceptThread" + socketType);
BluetoothSocket socket = null;
while (bluetoothState != STATE_CONNECTED) {
try {
socket = this.serverSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
synchronized (BluetoothService.this) {
switch (bluetoothState) {
case STATE_LISTEN:
case STATE_CONNECTING:
connected(socket, socket.getRemoteDevice(), socketType);
break;
case STATE_NONE:
case STATE_CONNECTED:
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
}
public void cancel() {
try {
this.serverSocket.close();
} catch (IOException e) {
Log.e(TAG, "Socket Type" + socketType + "close() of server failed", e);
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket bluetoothSocket = null;
private BluetoothDevice bluetoothDevice = null;
private String socketType = null;
public ConnectThread(BluetoothDevice bluetoothDevice, boolean secure) {
this.bluetoothDevice = bluetoothDevice;
this.socketType = secure ? "Secure" : "Insecure";
BluetoothSocket tempBluetoothSocket = null;
try {
if (secure) {
tempBluetoothSocket = this.bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tempBluetoothSocket = this.bluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + this.socketType + "create() failed", e);
}
this.bluetoothSocket = tempBluetoothSocket;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
this.setName("ConnectThread");
bluetoothAdapter.cancelDiscovery();
try {
this.bluetoothSocket.connect();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
connectionFailed();
try {
this.bluetoothSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
return;
}
synchronized (BluetoothService.this) {
connectThread = null;
}
connected(this.bluetoothSocket, this.bluetoothDevice, this.socketType);
}
public void cancel() {
try {
this.bluetoothSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private BluetoothSocket bluetoothSocket = null;
private InputStream inputStream = null;
private OutputStream outputStream = null;
public ConnectedThread(BluetoothSocket bluetoothSocket, String socketType) {
Log.d(TAG, "create ConnectedThread");
this.bluetoothSocket = bluetoothSocket;
InputStream tempInputStream = null;
OutputStream tempOutputStream = null;
try {
tempInputStream = this.bluetoothSocket.getInputStream();
tempOutputStream = this.bluetoothSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
this.inputStream = tempInputStream;
this.outputStream = tempOutputStream;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes = 0;
while (true) {
try {
bytes = this.inputStream.read(buffer);
handler.obtainMessage(Globals.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
BluetoothService.this.start();
break;
}
}
}
public void write(byte[] buffer) {
try {
this.outputStream.write(buffer);
handler.obtainMessage(Globals.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
this.bluetoothSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
When i now want to connect to a BluetoothDevice with this code:
private void connectDevice(Intent data, boolean secure) {
String address = data.getExtras().getString(BluetoothFragment.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = this.bluetoothAdapter.getRemoteDevice(address);
this.bluetoothService.connect(device, secure);
}
I get the following Error:
02-07 12:47:15.633: E/BluetoothService(17671): read failed, socket might closed or timeout, read ret: -1
02-07 12:47:15.633: E/BluetoothService(17671): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
02-07 12:47:15.633: E/BluetoothService(17671): at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:512)
So everything i do is exactly like the example which android is providing.
You can download the sample code of the BluetoothChat in the Android
Studio sample codes.
The only thing im curious about is the uuid. I dont know how to create them and if it is important to use a special uuid. I just used a uuid generator which i downloaded from the Android Play Store and did the following:
private static final UUID MY_UUID_SECURE = UUID.fromString("a6fb84f6-20b3-477f-9160-bcd028bddc99");
private static final UUID MY_UUID_INSECURE = UUID.fromString("7dd8441a-1d4b-42f1-9996-a7d507548dfc");
So the question is: How can i connect to a BluetoothDevice?
Addition
I use a Nexus 7 and a Nexus 4 with the latest Android Version.
I downloaded several bluetooth connection apps and all of these
apps arent able to build a connection between my devices. So
maybe it isnt a problem with the code? Is it a Nexus or Android
5.0.1 bug?
Can you try this code?
You can pass the string to the BT device by calling
BluetoothPrinterHelper.BT.send(context, data)
Note: The code assumes that you have connected and paired to the BT device and is the only device in the paired list. You can change this behaviour in the findDevice(BluetoothAdapter) method.
Also, the UUID can be generated in Java itself by calling UUID.randomUUID().toString(), but in this case UUID plays a different role. This identifies the profile the target BT device is running. You check more about that here BT-UUID
package com.example.bt;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.AsyncTask;
public enum class BluetoothPrinterHelper {
BT;
private BluetoothDevice device;
private static BluetoothSocket socket;
private BluetoothSocket tmp;
private BluetoothAdapter adapter;
private String deviceName;
public void send(Context ctx, String data) {
mTryConnect = new TryConnect();
mTryConnect.execute();
boolean isConnected = false;
try {
Log.d(TAG, "Establishing connection to device");
isConnected = mTryConnect.get();
} catch (InterruptedException e) {
Log.e(TAG, "Error connecting to device");
return;
} catch (ExecutionException e) {
Log.e(TAG, "Error connecting to device");
return;
}
if (isConnected) {
Log.d(TAG, "Connection to device successfully established");
mTrySend = new TrySend(data);
mTrySend.execute();
} else {
Toast.makeText(ctx, "No BT device connected", Toast.LENGTH_LONG).show();
}
}
private BluetoothDevice findDevice(BluetoothAdapter adapter) {
Log.d(TAG, "Finding BT devices");
Set<BluetoothDevice> pairedDevices = null;
try {
pairedDevices = adapter.getBondedDevices();
} catch (NullPointerException e) {
Log.e(TAG, "Error retrieving paired devices");
}
if (pairedDevices != null && pairedDevices.size() == 1) {
Log.d(TAG, "Found 1 paired device");
for (BluetoothDevice bluetoothDevice : pairedDevices) {
return bluetoothDevice;
}
} else {
Log.w(TAG, "Many/No paired BT devices found");
}
return null;
}
private class TryConnect extends AsyncTask<Void, Void, Boolean> {
public TryConnect() {
adapter = BluetoothAdapter.getDefaultAdapter();
}
#Override
protected Boolean doInBackground(Void... params) {
// Check bonded devices list
device = findDevice(adapter);
if (adapter.isDiscovering()) {
adapter.cancelDiscovery();
}
// Create a socket for the device connection
if (device != null) {
try {
deviceName = device.getName();
Log.d(TAG, "Creating socket");
tmp = device.createRfcommSocketToServiceRecord(DEVICE_UUID);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Printing - NoSuchMethodException", e);
return false;
} catch (IllegalArgumentException e) {
Log.e(TAG, "Printing - IllegalArgumentException", e);
return false;
} catch (IllegalAccessException e) {
Log.e(TAG, "Printing - IllegalAccessException", e);
return false;
} catch (InvocationTargetException e) {
Log.e(TAG, "Printing - InvocationTargetException", e);
return false;
}
}
socket = tmp;
// Connect to the created socket and device
try {
Log.d(TAG, "Creating connection to: " + deviceName);
socket.connect();
} catch (IOException e) {
Log.e(TAG, "Unable to connect. Closing connection", e);
try {
socket.close();
} catch (IOException e1) {
Log.e(TAG, "Unable to close connection during connection failure", e1);
}
return false;
} catch (NullPointerException e) {
Log.e(TAG, "NPE during BT socket connection");
}
return true;
}
}
private class TrySend extends AsyncTask<Void, Void, Boolean> {
byte[] out;
public TrySend(String data) {
try {
out = data.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
Log.w(TAG, "UnsupportedEncodingException");
}
}
#Override
protected Boolean doInBackground(Void... params) {
try {
// Get the output stream and ready for write
try {
Log.d(TAG, "Creating output stream");
outStream = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Socket not created", e);
return false;
} catch (NullPointerException e) {
Log.e(TAG, "NPE retreiving socket stream");
return false;
}
// Write data to the socket for printing
try {
Log.d(TAG, "Write to output stream");
// Write format
outStream.write(command);
// Write data to print
DataOutputStream dataOutputStream = new DataOutputStream(outStream);
dataOutputStream.write(out);
dataOutputStream.flush();
} catch (IOException e) {
Log.e(TAG, "Exception during BT write to device", e);
return false;
} catch (NullPointerException e) {
Log.e(TAG, "NPE during socket write");
} finally {
try {
outStream.close();
} catch (IOException e) {
Log.e(TAG, "Exception during closing outstream", e);
} catch (NullPointerException e) {
Log.e(TAG, "NPE during BT socket close");
}
}
// Close the socket and cleanup
try {
Log.d(TAG, "Closing socket");
socket.close();
} catch (IOException e) {
Log.e(TAG, "Socket closing exception", e);
return false;
} catch (NullPointerException e) {
Log.e(TAG, "NPE during BT socket close");
}
} finally {
adapter = null;
device = null;
socket = null;
outStream = null;
}
return true;
}
}
}
UPDATE: Can you try this code:
Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, 1);
instead of
tmp = device.createRfcommSocketToServiceRecord(DEVICE_UUID);
I wish to build a simple peer-peer app using Sockets. A accepts a number and sends it to B. Then B returns the square of the number back to A.
A sends to B on port 6000 and B sends back to A on port 8000. So both the machines act as clients when they must send, and as servers when they must receive.
But isn't it true that a server should be started BEFORE a client ? So, whats the logical solution to making this app ?
Here is the Server's code
package com.javacodegeeks.android.androidsocketserver;
.....
public class Server extends Activity {
private ServerSocket serverSocket;
private Socket clientSock;
Handler updateConversationHandler;
Thread serverThread = null;
Thread clientThread = null;
private TextView text;
public static final int SERVERPORT = 5000;
public static final int CLIENTPORT = 8000;
private static final String CLIENT_IP = "10.0.2.2";
protected IRemote mService;
private boolean bound = false;
Intent it;
private boolean test = false;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
mService = null;
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_SHORT).show();
Log.d("IRemote", "Binding - Service disconnected");
}
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
// TODO Auto-generated method stub
mService = IRemote.Stub.asInterface((IBinder) service);
Toast.makeText(getApplicationContext(), "yes", Toast.LENGTH_SHORT).show();
Log.d("IRemote", "Binding is done - Service connected");
}
};
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
it = new Intent();
it.setAction("com.example.mynewclient.RemoteService");
//it= new Intent(this,IRemote.class);
//TEMP
bound = getApplicationContext().bindService(it, mServiceConnection, Context.BIND_AUTO_CREATE);
Log.d("SERVER", bound ? "Binding is done - Service connected" : "Binding Failed");
this.clientThread = new Thread(new ClientThread());
this.clientThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onClick(View view) {
try {
// EditText et = findViewById(R.id.text);
String str = text.getText().toString();//et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(clientSock.getOutputStream())),
true);
out.println(345+"\n");
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Exception 1", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Exception 2", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Exception 3", Toast.LENGTH_LONG).show();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
BufferedWriter writer;
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
//writer = new BufferedWriter(new OutputStreamWriter(this.clientSocket.getOutputStream()));
//writer.write("Server Echos to client");
//writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run(){
String message;
BufferedReader input;
if(mService == null)
{
Log.d("TAG 0", "Inside mservice==null");
Intent it = new Intent();
it.setAction("com.example.mynewclient.RemoteService");
//it.setClassName( "com.example.myclient","com.example.myclient.IRemoteService" );
//binding to remote service
// bindService(it, mServiceConnection, Service.BIND_AUTO_CREATE);
}
int f = Integer.parseInt(msg);
try{
//Toast.makeText(getApplicationContext(), "Result -> Add ->"+mIRemoteService.getSum(3,4), Toast.LENGTH_SHORT).show();
message = Integer.toString(mService.getSum(f,f));
text.setText(text.getText().toString()+"The sum is: "+ message + "\n");
}
catch(Exception e)
{
//setContentView(R.layout.activity_main);
System.out.println(e.toString());
Log.e("EXCEPTION 3", e.toString());
f = f+f;
message = "Not Successful";
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
//TEMP Commented
/*#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}*/
}
class ClientThread implements Runnable {
#Override
public void run() {
BufferedReader input;
try {
Log.d("SERVER", "Client - thread 1");
InetAddress serverAddr = InetAddress.getByName(CLIENT_IP);
clientSock = new Socket(serverAddr, SERVERPORT);
//input = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
/////////////////////
Log.d("SERVER", "Client - thread 2");
//TEMP Commented
//input = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
input = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
Log.d("SERVER", "Client - thread 3");
} catch (UnknownHostException e1) {
e1.printStackTrace();
Toast.makeText(getApplicationContext(), "exception 1", Toast.LENGTH_SHORT).show();
} catch (IOException e1) {
e1.printStackTrace();
Toast.makeText(getApplicationContext(), "exception 2", Toast.LENGTH_SHORT).show();
}
}
}
}
Here's the client:
package com.javacodegeeks.android.androidsocketclient;
....
public class Client extends Activity {
private Socket thisSocket;
private ServerSocket serverSocket;
private TextView text;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "10.0.2.2";
private static final int CLIENTPORT = 8000;
Handler updateConversationHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
new Thread(new ServerThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(thisSocket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
Log.e("SERVER ERROR",e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("SERVER ERROR",e.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("SERVER ERROR",e.toString());
}
}
class ClientThread implements Runnable {
#Override
public void run() {
BufferedReader input;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
thisSocket = new Socket(serverAddr, SERVERPORT);
input = new BufferedReader(new InputStreamReader(thisSocket.getInputStream()));
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//TEMP COMMENTED
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(CLIENTPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
Log.d("CLIENT TAG", "Listening to server");
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
Log.d("TAG Client 1", "IOException");
}
catch (Exception e)
{
Log.d("TAG Client 2", e.toString());
}
}
Toast.makeText(getApplicationContext(), "Client interrupted", Toast.LENGTH_LONG).show();
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
Log.d("TAG Client 4", "Input from server"+input.toString());
} catch (IOException e) {
Log.d("TAG Client 5", "Input from server");
e.printStackTrace();
}
catch (Exception e)
{
Log.d("TAG Client 6", "Input from server");
}
}
public void run() {
BufferedWriter writer;
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
//writer = new BufferedWriter(new OutputStreamWriter(this.clientSocket.getOutputStream()));
//writer.write("Server Echos to client");
//writer.close();
Log.d("TAG Client 7", "Input from server");
} catch (IOException e) {
e.printStackTrace();
Log.d("TAG Client 8", e.toString());
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
//text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
}
The distinction between client and server is not made by who is sending or receiving data. In many cases, both server and client do both. The point of peer-to-peer is that there is no server/client relationship.
That being said, both your applications should run and start listening before you send anything, unless it's always A that sends first, in which case you have a client/server relationship.
Hope that helps.
Edit: Should probably mention this: You usually use multiple threads for networking, to keep listening on at least one port while the rest of the program executes.
There should be a long-connection Server for each client(like A,B,C,D.....),A send msg to Server and forward to D.
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);
}
}
}
}
}