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;
}
}
Related
I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} 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();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.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();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}
Server: PC
Client: Android
So my Client/Server app consists in opening webpages and executing a bot, everything is fine if I use only for a router, but I would like to be able to to connect in different places (different router/PC).
I was searching for "Wi-fi Search of IP" and got nothing.
Is it possible to give to the Server side a fix IP? like always 192.168.1.68?
Client Code
public class AndroidClient extends Activity
{
EditText episode;
Spinner spinner1;
String result;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
episode = (EditText) findViewById(R.id.episode);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
spinner1 = (Spinner) findViewById(R.id.Animes);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Anime, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
addListenerOnSpinnerItemSelection();
addListenerOnButton();
}
public void addListenerOnSpinnerItemSelection() {
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.Animes);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask();
myClientTask.execute();
}
});
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.1.3.68", 8080);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(episode.getText() + "-" + String.valueOf(spinner1.getSelectedItem()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Server Code
public class ServerSide extends Application
{
TextField textTitle;
Label labelSys, labelPort, labelIp;
Label labelMsg;
CheckBox optWelcome;
ServerSocket serverSocket;
String message = "";
String result;
#Override
public void start(Stage primaryStage) {
textTitle = new TextField();
labelSys = new Label();
labelPort = new Label();
labelIp = new Label();
labelMsg = new Label();
labelIp.setText(getIpAddress());
VBox mainLayout = new VBox();
mainLayout.setPadding(new Insets(5, 5, 5, 5));
mainLayout.setSpacing(5);
mainLayout.getChildren().addAll(textTitle,
labelSys, labelPort, labelIp,
labelMsg);
StackPane root = new StackPane();
root.getChildren().add(mainLayout);
Scene scene = new Scene(root, 300, 400);
primaryStage.setTitle("One Piece");
primaryStage.setScene(scene);
primaryStage.show();
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.setDaemon(true);
socketServerThread.start();
}
public static void main(String[] args) {
launch(args);
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
Socket socket = null;
serverSocket = new ServerSocket(SocketServerPORT);
Platform.runLater(new Runnable() {
#Override
public void run() {
labelPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
count++;
//Start another thread
//to prevent blocked by empty dataInputStream
Thread acceptedThread = new Thread(
new ServerSocketAcceptedThread(socket, count));
acceptedThread.setDaemon(true); //terminate the thread when program end
acceptedThread.start();
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class ServerSocketAcceptedThread extends Thread {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
int count;
ServerSocketAcceptedThread(Socket s, int c) {
socket = s;
count = c;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
//If dataInputStream empty,
//this thread will be blocked by readUTF(),
//but not the others
String messageFromClient = dataInputStream.readUTF();
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
Platform.runLater(new Runnable() {
#Override
public void run() {
labelMsg.setText(message);
}
});
String string = messageFromClient;
String[] parts = string.split("-");
String episode = parts[0];
String anime = parts[1];
String OneP = new String("One Piece");
String Naruto = new String ("Naruto");
String Bleach = new String ("Bleach");
int EPnumb = Integer.parseInt(episode);
if (EPnumb < 10) {
result = "00" + episode;
}
else if (EPnumb < 100 && EPnumb >= 10) {
result = "0" + episode;
}
else { result = episode; }
if (anime.equals(OneP)){
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/One-Piece/Episode-"+ result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}}
else {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/Naruto-Shippuuden/Episode-"+result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
private java.lang.String parseInt(java.lang.String episode) {
// TODO Auto-generated method stub
return null;
}
private 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 += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
return ip;
}
public DataInputStream String(String string) {
return null;
}
}
You can use ServerSocket(int port, int backlog, InetAddress bindAddr)
Constructs a new ServerSocket instance bound to the given localAddress and port.
I've a simple client and server on android. Everything works fine except when I close the client app then the server stops working the app closes.
I think it's about not closing the socket. But when I close the socket in the client the server still stops working.
I'm running a thread on the server. This is my server code:
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
private boolean feedback = false;
public updateUIThread(String str) {
msg = str;
}
#Override
public void run() {
parseCommand();
if(feedback)
{
textFeedback.setText(msg);
feedback = false;
}
else
{
textTv.setText(msg);
}
}
if(msg != null)
parseCommand();
and in
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
if(read == null)
{
clientSocket.close();
Log.d("Test","SOCKET CLOSED");
return;
}
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
I have a simple connection activity:
package com.example.conn08;
import ...;
public class MainActivity extends Activity
{
public static Socket clientSocket;
public static DataOutputStream outToServer;
public static PrintWriter outTest;
public static BufferedReader inToServer;
With PrintWriter outTest I test server's availability:
If the user has no Internet, or the server doesn't work, I put Thread on a pause with Boolean shouldContinue.
private Thread mThread;
private final Object lock = new Object();
private Boolean shouldContinue = true;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThread = new Thread(new Runnable()
{
public void run()
{
while (true)
{
synchronized(lock)
{
try
{
lock.wait(); // lock the Thread
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (shouldContinue)
{
try
{
final String data = inToServer.readLine();
if (data != null)
{
Log.v("data", data);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
String put[] = data.split("#");
//Data parsing
}
});
}
}
catch (IOException e)
{
e.printStackTrace();
}
Check on availability of the server:
try {
if(clientSocket.getInputStream().read() == -1)
{
Log.v("Connection: ", "lost");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
mThread.start();
Connect();
}
public void Connect()
{
shouldContinue = true;
try
{
clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("localhost", 15780), 30000);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inToServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
outTest = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream())), true);
synchronized(lock)
{
lock.notify();
}
sendUTF("3#kokoko"); //send the message!
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void sendUTF(String str)
{
try
{
byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();
}
catch (IOException e)
{
e.printStackTrace();
outServ.setText("Нет соединения!");
}
}
}
Problem in that when I don't use the
if(clientSocket.getInputStream().read() == -1)
And send data to server like here:
sendUTF("3#kokoko");
All is fine, but if I use it, on server I see this message like
"#kokoko" - I lose the first character of the message and my socket is crushed! Help me please
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);
}
}
}
}
}