i am building app which will become server and other 3 or 5 phones become client. and from server i will send code for instruction all device click photo at same time. i am confusing how to do that..i have tcp/udp but it only connect 1 device but i want multiple device.
class MyServer implements Runnable
{
ServerSocket serverSocket;
Socket socket;
DataInputStream dataInputStream;
String msg="";
Handler handler=new Handler();
#Override
public void run() {
try {
serverSocket=new ServerSocket(9700);
while (true)
{
socket=serverSocket.accept();
dataInputStream=new DataInputStream(socket.getInputStream());
msg= dataInputStream.readUTF();
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Backgroundtask extends AsyncTask<String,Void,String>
{
Socket socket;
DataOutputStream dataOutputStream;
String ip,msg;
#Override
protected String doInBackground(String... strings) {
ip=strings[0];
msg=strings[1];
try {
socket=new Socket(ip,9700);
dataOutputStream=new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(msg);
dataOutputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
i want when i am trigger instruction from server all device must follow at same time.
Related
I am using this code please suggest me any link and any kind of books related to my question. this code is working fine but it is used to send only text after fetching from a textview between two devices using wifi direct.
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg=writeMsg.getText().toString();
sendRecieve.write(msg.getBytes());
}
});
public class ServerClas extends Thread{
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try{
serverSocket=new ServerSocket(8888);
socket=serverSocket.accept();
sendRecieve=new SendRecieve(socket);
sendRecieve.start();
}catch (IOException e){
e.printStackTrace();
}
}
}
public class SendRecieve extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendRecieve(Socket skt){
socket=skt;
try{
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer=new byte[1024];
int bytes;
while (socket!=null){
try{
bytes=inputStream.read(buffer);
if( bytes>0){
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress){
hostAdd=hostAddress.getHostAddress();
socket=new Socket();
}
#Override
public void run() {
try{
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendRecieve=new SendRecieve(socket);
sendRecieve.start();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
I think you should use this API
I am trying to create a connection between two applications using android. I have tried to use sockets to connect. I have created two application
One which accepts the connection when client wants to connect
and another application that requests to connect.
I have successfully run this code in same manner in pc in java in pc network. Is the way of connecting to android also same?
My server class implementation
public class MainActivity extends AppCompatActivity {
private Button startButton;
private ServerSocket server;
private Socket connection;
private TextView statusText;
private ObjectOutputStream output;
private ObjectInputStream input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
statusText=(TextView)findViewById(R.id.statusText);
startButton=(Button)findViewById(R.id.startButton);
startButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
startRunning();
}
}
);
}
private void startRunning() {
try{
server=new ServerSocket(8080);
while(true)
{
try{
waitForConnection();
setUpStreams();
whileChatting();
}catch(Exception e){}
}
} catch(Exception e){}
}
public void waitForConnection()
{
setMyStatus("Waiting for client to connect...");
try {
connection= server.accept();
setMyStatus("Now connected to "+ connection.getInetAddress().getHostName());
} catch (IOException e) {
e.printStackTrace();
}
}
public void setUpStreams()
{
try {
output= new ObjectOutputStream(connection.getOutputStream());
output.flush();
input= new ObjectInputStream(connection.getInputStream());
setMyStatus("Streams are now setup. Ready to go...");
} catch (IOException e) {
e.printStackTrace();
}
}
public void whileChatting()
{
setMyStatus("You can now start chatting...");
}
public void setMyStatus(String msg) {
statusText.setText(msg);
}
}
I will use the tasks like async task later. But i am just trying to set up connection in these application.
My client implementation goes like this
public class MainActivity extends AppCompatActivity {
private Button startButton;
private Socket connection;
private TextView statusText;
public ObjectOutputStream output;
public ObjectInputStream input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
statusText=(TextView)findViewById(R.id.statusText);
startButton=(Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRunning();
}
});
}
private void startRunning() {
connectToServer();
setUpStreams();
whileChatting();
}
public void connectToServer()
{
setMyStatus("Connecting to server. Please wait...");
try {
connection= new Socket(InetAddress.getByName("127.0.0.1"),8080);
setMyStatus("Connected to Server."+ connection.getInetAddress().getHostName());
} catch (IOException e) {
e.printStackTrace();
}
}
public void setUpStreams()
{
try {
output= new ObjectOutputStream(connection.getOutputStream());
output.flush();
input= new ObjectInputStream(connection.getInputStream());
setMyStatus("Streams are now setup. Ready to go...");
} catch (IOException e) {
e.printStackTrace();
}
}
public void whileChatting()
{
setMyStatus("You can now start chatting...");
}
public void setMyStatus(String msg) {
statusText.setText(msg);
}
}
The error I got is in the case of client that tries to connect to server
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream java.net.Socket.getOutputStream()' on a null object reference
at com.myapp.client.clientdemo.MainActivity.setUpStreams(MainActivity.java:71)
at com.myapp.client.clientdemo.MainActivity.startRunning(MainActivity.java:46)
at com.myapp.client.clientdemo.MainActivity.access$000(MainActivity.java:16)
at com.myapp.client.clientdemo.MainActivity$1.onClick(MainActivity.java:33)
It's because "connection" was never created. Probably because it failed to connect or it timed out and it moved on to the next code. If it timed out or didn't connect, then you need to catch that exception and retry to connect before moving on with your later code.
Socket can be tricky if you do not catch all the erroneous states they can get into.
simply wrap your try and catch with a while loop until the condition is met like this:
while(!connected & !closed){
try {
connection= new Socket(InetAddress.getByName("127.0.0.1"),8080);
connected = true;
//now it is connected and will exit the loop and continue with other code
} catch (SocketTimeoutException socketTimeoutException) {
//add this for safety
} catch (IOException e) {
e.printStackTrace();
}
}
I have made an application that opens up a socket via a thread and updates based on what is typed. Here is the code:
Server.java:
public class Server {
public static void main(String[] args) throws IOException {
int portNumber = 2392;
boolean listening = true;
System.out.println("Server: Running...");
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
System.out.println("Server: Connected to Client!");
while (listening) {
new ServerThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection( '" + e.getMessage() + "' );");
} finally {
System.out.println("Server: Disconnecting...");
}
}
}
Server Thread.java:
public class ServerThread extends Thread {
private Socket socket = null;
Scanner reader = new Scanner(System.in);
public ServerThread(Socket socket) {
super("ServerThread");
this.socket = socket;
}
public void run() {
System.out.println("Ruasd");
try (PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
String outputLine = "";
while (!outputLine.equals("Disconnect")) {
outputLine = reader.nextLine();
out.println(outputLine);
}
socket.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java:
public class MainActivity extends Activity {
private Socket socket;
private TextView status;
private BufferedReader in;
private Handler mHandler;
private static final int SERVERPORT = 2392;
private static final String SERVER_IP = "...ip#...";
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_vitals);
status = (TextView) findViewById(R.id.text_status);
new Thread(new CommunicationThread()).start();
}
#Override
protected void onStop() {
super.onStop();
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
final String fromServer = in.readLine();
System.out.println("Server: " + fromServer);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
status.setText(fromServer);
}
});
if (fromServer.equals("Disconnect."))
break;
}
} catch (IOException e) {
e.printStackTrace();
}
It works perfectly the first time and outputs to the status TextView correctly. However, when I restart the application, it outputs every other word. For instance, If I type "Hey" "Hi "You" "How", I will see "Hi" and "How" in the TextView the second time I start the application.
What's really odd to me is that when I do System.out.println("Server: " + fromServer) it is outputting all values. Any suggestions are greatly appreciated.
Ok I think I found the problem (got it working for me, that is). In your CommunicationThread, you didn't have a while loop. Also, you need to iterate the server's input until it is null. See below:
class CommunicationThread implements Runnable {
#Override
public void run() {
try {
// keep the connection alive.
while (true) {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String fromServer;
// get server messages until there are none
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
status.setText(fromServer);
}
});
if (fromServer.equals("Disconnect."))
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please get back to me on how it works out :)
I tried to write a simple server for an app that user can write a message from PC using telnet to IP and port. IT works just fine and it can show the
The problem is, when user closes telnet window (CMD window in PC, there is where user connects to app) the app stops.
Is there a way to prevent this behaviour? Here is my code:
//Defined in Activity class
//Sockets, servers, clients and stuff
public java.net.ServerSocket MyServerSocket;
public String IpAddress = "";
public int Port = 12345;
public Handler UpdateConversationHandler;
public Thread ServerThread = null;
Nested classes inside the Activity class:
class ServerThread implements Runnable{
public final String IpAddress;
public final int Port;
public ServerThread(String ipAddress, int port)
{
IpAddress = ipAddress;
Port = port;
}
public void run() {
Socket socket = null;
try{
MyServerSocket = new ServerSocket(Port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.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;
public UpdateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
_textview_info.setText("Client Says: "+ msg );
}
}
I also have this code for onStop method, but it doesn't help!
#Override
protected void onStop() {
super.onStop();
//Closing server socket
try
{
MyServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And this is the onCreate method, where the server starts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_context = this;
//Prepare spinners
_preferences = getSharedPreferences("org.pervasivesystems.nexusmosaic", MODE_PRIVATE);
_preferencesEditor = _preferences.edit();
_spinner_videos = (Spinner) findViewById(R.id.spinner_select_video);
_spinner_ids = (Spinner) findViewById(R.id.spinner_select_id);
populateSpinners();
//Prepare server
IpAddress = getIpAddress();
TextView tvIpAddress = (TextView) findViewById(R.id.textview_ip_address_value);
tvIpAddress.setText(IpAddress);
_textview_info = (TextView) findViewById(R.id.textview_information);
UpdateConversationHandler = new Handler();
ServerThread = new Thread(new ServerThread(IpAddress, Port));
this.ServerThread.start();
}
UPDATE
When I start the app, even before connecting from PC to app using telnet, I get the following message continuesly in LOGCAT:
11-14 15:45:32.460 W/System.err? at java.lang.Thread.run(Thread.java:856)
11-14 15:45:32.460 W/System.err? java.net.SocketException: Socket is closed
11-14 15:45:32.460 W/System.err? at java.net.ServerSocket.checkOpen(ServerSocket.java:362)
11-14 15:45:32.460 W/System.err? at java.net.ServerSocket.accept(ServerSocket.java:120)
11-14 15:45:32.460 W/System.err? at .MainActivity$ServerThread.run(MainActivity.java:233)
Line 233 is refering to this code:
while(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept(); //LINE 233
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
I also found out that after closing the telnet window from PC, the UpdateUiThread keeps running.
What is probably happening is that your communication thread is noticing the terminated connection and exits. This is how you wrote it. Im not sure what you want it to do instead...
If you want to do something after the terminated connection, just put some code right after
while(!Thread.currentThread().isInterrupted()){ ... }
Wait for the thread to finish, then do what you want.
Sometimes it helps me to add some system outs throughout threaded code to get a handle of when things are firing off/ending. It will help, trust me.
Try this
do{
if(!Thread.currentThread().isInterrupted()){
try{
socket = MyServerSocket.accept();
if(socket!=null && socket.isConnected()){
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}while(socket!=null && socket.isConnected());
I'm new at developing at android OS. I try developing my telnet client for android OS.
Now, I only try to connect telnet server, and receive login message.
But when I start socket to connect telnet server Ihave received strange symbols ??????!???? instead the logon message from telnet server.
public class MainActivity extends Activity {
protected static final int TCP_SERVER_PORT = 23;
protected String inMsg, str;
static Editable sentence;
static String modifedSentence;
BufferedReader inFromUser;
Socket clientSocket = null;
DataOutputStream outToServer=null;
BufferedReader inFromServer=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button)findViewById(R.id.startButton);
final TextView textView = (TextView)findViewById(R.id.textView);
startButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
new Thread(new Runnable() {
#Override
public void run() {
//Create socket
try {
clientSocket = new Socket("192.168.1.1",23);
//Create out stream for ClientSocket
outToServer = new DataOutputStream(clientSocket.getOutputStream());
//Create ib stream for ClientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//Receive login message from telnet server
modifedSentence = inFromServer.readLine();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Update UI activity with login message
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(modifedSentence);
}
});
}
}).start();
}
});
}
protected void onDestroy()
{
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
These "strange" symbols ??????!???? mean, that you use wrong encoding. When you create InputStreamReader you should explicitly point which encoding this stream should use. I don't known which encoding is used inside your telnet service, but you can try various of them, e.g. windows-1252:
new InputStreamReader(clientSocket.getInputStream(), Charset.forName("windows-1252"))
Telnet app require telnet protocol for connections to the telnet server. It's not a simple tcp connection. I use apache commonse library which provide class for telnet accessing.
Thanks