After asking so many question about android socket programming and getting valuable answers from stackoverflow's members i could do a well working program using sockets to connect two device over wifi.
Thanks to all.
But still i am having some problem..
i have done the program in which
** Data can be sent from client and received at serverSocket**
But still i am not getting how to Send data from server which can be received at client
Code for Server Socket
private OnClickListener bt_sendListner = new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String msg=et_msg.getText().toString();
Log.d("Msg", msg);
Thread threadsendmsg = new Thread(new Threadsendmsg(msg));
threadsendmsg.start();
}
};
public class Threadsendmsg implements Runnable{
String msg;
public Threadsendmsg(String msg) {
// TODO Auto-generated constructor stub
this.msg=msg;
}
public void run() {
// TODO Auto-generated method stub
try {
Looper.prepare();
Log.d("Msg", "Inside the thread");
//connected = true;
while (true) {
try {
Log.d("Msg", "Msg to be sent");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(serverSocket.accept().getOutputStream())), true);
// where you issue the commands
out.println("Client: "+msg);
Log.d("Msg", "Msg sent"+out.toString());
break;
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
tv_chatbox.setText("S: Error= "+ e.getMessage());
Log.d("Msg", e.getMessage());
}
});
}
}
// socket.close();
// console.append("\nC: Closed.");
} catch (final Exception e) {
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
tv_chatbox.setText("S: Error= "+ e.getMessage());
Log.d("Msg", e.getMessage());
// TODO Auto-generated method stub
// console.append("\nC: Error= "+ e.getMessage());
}
});
// connected = false;
}
}
}
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();
}
}
}
*There is no method as ServerSocket.getOutputStream() in ServerSocket class.*Which i have used client socket...
Both client and server use the same class Socket. But client creates his socket instance manually and connects to server. Server on the other hand listens at some port and when client connects, socket for server is created and returned from method accept().
In your code you can use
client.getOutputStream();
Related
I am trying to make a wifi p2p video chat application.I can establish a wifi-p2p connection and I made a simple wifi p2p text chat application. How to capture the video , send and receive it?
I have tried the following code.
When I try to run this , it always gives some exception such as :illegalstateexception mediarecorder.start() or java.net.UnknownHostException
Sender Thread:
public class SendVideoThread implements Runnable{
public void run(){
try {
if(SERVERIP!=null){
handler.post(new Runnable() {
#Override
public void run() {
}
});
serverSocket = new ServerSocket(SERVERPORT);
while(true) {
//listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable(){
#Override
public void run(){
}
});
try{
final ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(client);
handler.post(new Runnable(){
#Override
public void run(){
recorder = new MediaRecorder();
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile(pfd.getFileDescriptor());
recorder.setVideoFrameRate(20);
recorder.setVideoSize(176,144);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
//recorder.setPreviewDisplay(mHolder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
}
});
} catch (Exception e) {
handler.post(new Runnable(){
#Override
public void run(){
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run(){
}
});
}
} catch (Exception e){
handler.post(new Runnable() {
#Override
public void run() {
}
});
e.printStackTrace();
}
}
}
Receiver Thread:
public class ReceiveVideoThread implements Runnable{
#Override
public void run() {
try {
clientSocket = new Socket(Data.socket.getInetAddress(),SERVERPORT);
handler.post(new Runnable() {
#Override
public void run() {
}
});
handler.post(new Runnable() {
#Override
public void run() {
try {
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(clientSocket);
pfd.getFileDescriptor().sync();
mp.setDataSource(pfd.getFileDescriptor());
pfd.close();
mp.setDisplay(mHolder);
mp.prepareAsync();
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have tried updating my user interface using the text view what i have done is a run a while loop indefinitely and left the thread for sleep for one second..
int i;
while(true)
{
Thread.Sleep(1000);
textView.setText(updateTime);
}
Use runOnUiThread and surround with try catch for Thread.sleep(1000)
int i;
while(true)
{
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textView.setText(updateTime);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try this one arnab...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.displayid);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
bundle = msg.getData();
textView.setText(bundle.getString("mKey"));
}
};
}
public void press(View v) {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bundle = new Bundle();
message = handler.obtainMessage();
simpleDateFormat = new SimpleDateFormat("hh:mm:ss YYYY/mm/dd", Locale.US);
date = simpleDateFormat.format(new Date());
bundle.putString("mKey", date);
message.setData(bundle);
handler.sendMessage(message);
}
}
}
}).start();
}
Try runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateTime);
}
});
I have this thread wating for onTouchEvent()
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Your session expired Please Login again",Toast.LENGTH_SHORT).show();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
final Logout l=new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to Logout.java
l.execute(sessid,uname);
}
});
}
};
what i want is notify this waiting thread when user touches a mobile screen..
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Your session expired Please Login again",
Toast.LENGTH_SHORT).show();
try {
synchronized (disconnectCallback) {
disconnectCallback.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
final Logout l = new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to
// Logout.java
l.execute(sessid, uname);
}
});
}
};
and in onTouch event call:
disconnectCallback.notifyAll();
Try this
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Your session expired Please Login again",
Toast.LENGTH_SHORT).show();
}
});
try {
synchronized(disconnectCallback){
disconnectCallback.wait();
final Logout l=new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to Logout.java
l.execute(sessid,uname);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Inside onTouch
synchronized (disconnectCallback) {
disconnectCallback.notify();
}
I have a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.
I'm trying to automatically refresh JmDNS services in the background. Nothing is happening when I try:
#Override
public void onDestroy() {
try {
hiNeighborService.unregisterListener(this);
this.unbindService(this.serviceConnection);
} catch (Exception ex) {
Log.e(LOG_TAG, "Exception occur during destroying the app.");
}
super.onDestroy();
}
#Override
public void onStart() {
/*new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onStart();
}
#Override
public void onRestart() {
/*new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onRestart();
}
#Override
public void onResume() {
/*new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
refreshServices();
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();*/
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
rebindService();
refreshServices();
}
}, 0, 1, TimeUnit.SECONDS);
super.onResume();
}
This is my resfreshServices() method:
private void refreshServices() {
Log.i(LOG_TAG, "Refresh available neighbors...");
final List<Neighbor> activeNeighbors = this.hiNeighborService
.getActiveNeighbors();
Log.d(LOG_TAG, activeNeighbors.size() + " active neighbors are found!");
new Thread(new Runnable() {
public void run() {
Log.i(LOG_TAG, "refresh UI...");
try {
synchronized (activeNeighborsViewModel) {
activeNeighborsViewModel.clear();
for (Neighbor neighbor : activeNeighbors) {
NeighborViewModel vm = new NeighborViewModel(
neighbor);
vm.setNeighborUnreadCount(ConnectActivity.this
.getUnreadMessageCount(neighbor));
if (activeNeighborsViewModel.contains(vm)) {
activeNeighborsViewModel.remove(vm);
}
activeNeighborsViewModel.add(vm);
}
}
notifyServiceListChanged();
Log.i(LOG_TAG, "refresh completed!");
} catch (Exception ex) {
ex.printStackTrace();
Log.e(LOG_TAG, ex.toString());
}
}
}).start();
}
Normally that gets call when a button is clicked however I would like it to be automatic. This code doesn't do anything unless I hit the Resfresh button that call resfreshServices(). I attempted to try it with threads but the activity closes and so does the app. Any ideas?
First a little comment on your code. Why are you implementing the same code three times in three different methods. I assume that you are programming android (loking at your method names). The method onresume is executed every time the activity is started or resumed. See this link for more information on this topic.
Ok, then... Did you already check the docs for more information about the ScheduledExecutorService?
Now for the jmdns issue. The jmDns library has a build in functionality to update the services. you can listen to new services and take the appropriate action when new services are available. I do not think, that repeated polling of the services is the right approach.
Look here for a little tutorial on using jmdns in android.