I'm trying to develop my first app in Android Studio and connect it to a server in python. I wrote a Client class and MainActivity with java in Android Studio and I wrote the Server in Pycharm. When I create a client object in different class, the connection between the client and the server works fine. However, when i do the same thing in the MainActivity it doesnt work and i get this error:
" E/m.example.mage: Unknown bits set in runtime_flags: 0x8000 ".
Do i need to do something else or is there a way to fix it?
package com.example.magen;
import android.widget.TextView;
import java.util.*;
import java.net.*;
import java.io.*;
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("connected to server");
}
catch(Exception e){
System.out.println("error 1 " + e.getMessage());
}
}
public String sendMessage(String msg) {
String resp="";
try {
out.println(msg);
System.out.println("client: "+msg);
resp = in.readLine();
}
catch(Exception e){
System.out.println("error 2 " + e.getMessage());
}
return resp;
}
public void stopConnection() {
try {
in.close();
out.close();
clientSocket.close();
}
catch(Exception e){
System.out.println("error 3 " + e.getMessage());
}
}
}
import socket
import select
import datetime
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 6969))
server_socket.listen(10)
open_client_sockets = []
def main():
while True:
rlist, wlist, xlist = select.select([server_socket]+open_client_sockets, open_client_sockets, [])
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
open_client_sockets.append(new_socket)
else:
full_msg = current_socket.recv(1024).decode()
print(full_msg)
current_socket.send("hi".encode())
...
...
...
...
...
if __name__ == '__main__':
main()
package com.example.magen;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText username;
private EditText password;
private Button loginButton;
private Button registerButton;
private TextView tvInfo;
private Client client = new Client();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.etUsername);
password = (EditText)findViewById(R.id.etPassword);
loginButton = (Button)findViewById(R.id.loginButton);
registerButton = (Button)findViewById(R.id.registerButton);
tvInfo = (TextView)findViewById(R.id.tvInfo);
connectToServer(client);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(username.getText().toString(), password.getText().toString(),tvInfo);
}
});
}
private void connectToServer(Client client){
client.startConnection("127.0.0.1", 6969);
String resp = client.sendMessage("hello");
tvInfo.setText(resp);
}
private void validate(String name, String password, TextView tvInfo){
if(name.equals("king_mageni") && password.equals("123456789")){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("username",name);
startActivity(intent);
}
else{
String errorMassage = "Incorrect username or password!";
tvInfo.setText(errorMassage);
}
}
}
Related
So basically I want to create some kind of controller for my pc, where on pc, runs java socket server. The server is working, I have tried it. Also, Port Forwarding in the router is allright. Source code is here :
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_BOLD = "\033[1m";
public static final String ANSI_RED = "\u001B[31m";
public static void main(String[] args) throws IOException {
// Creating server instance
ServerSocket serverSocket = new ServerSocket(2000);
Socket socket = serverSocket.accept();
System.out.println(ANSI_GREEN + "Controller connected" + ANSI_RESET);
// Input Output streams
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
String command = "";
do {
command = dataInputStream.readUTF();
switch (command.trim()){
case "volume up":
Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\volup.bat");
break;
case "volume down":
Runtime.getRuntime().exec("cmd /c start src\\sk\\dzurik\\main\\voldown.bat");
break;
default:
// Unknown command
break;
}
}while (!command.equals("stop"));
socket.close();
System.out.println(ANSI_RED + "Controller disconnected" + ANSI_RESET);
}
}
And it is supposed to interact with the android app, but I got an error and I can't quite figure out why is that so, here is the source code for ActivityMain :
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private boolean connected;
private DataOutputStream dataOutputStream;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pripájanie na server
try {
socket = new Socket("172.0.0.1",2000);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Not Connected!",
Toast.LENGTH_LONG).show();
}
Button VolumeUp = (Button) findViewById(R.id.VolumeUpButton);
VolumeUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("volume up");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button VolumeDown = (Button) findViewById(R.id.VolumeDownButton);
VolumeDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("volume down");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Button DisconnectButton = (Button) findViewById(R.id.DisconnectButton);
DisconnectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
send("stop");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void send(String command) throws IOException {
if (socket != null){
dataOutputStream.writeUTF(command);
}
else Toast.makeText(MainActivity.this, "Socket is not defined",
Toast.LENGTH_SHORT).show();
}
public void disconnect() throws IOException {
if (socket != null){
socket.close();
}
else Toast.makeText(MainActivity.this, "Socket is not defined",
Toast.LENGTH_SHORT).show();
}
}
So if you could help me with it, I would be thankful, <3
Well the reason for that was silly. When I'm loading data from Stream it says nextLine which means the ending point is \n so I could never get that line because I haven't put it there.
So,It's like the title Say's i have created a Simple android Socket server and Client which Connects over Wifi. Both devices are on the same Wifi Network. The Server Shows the IP Address on which it host the connection....And in the client You have to write the IP Address on which Server is hosted.....
So, My problem is when i am Entering The IP Address in the Client The Server shows "Connected". But when i start to send messages it doesn't send the message to other side neither Server to Client nor Client to server.
//#Server Java File
package inc.teckzy.wif_chat;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Helper extends AppCompatActivity {
EditText smessage;
TextView chat,display_status;
String str,msg="";
int serverport = 6666;
ServerSocket serverSocket;
Socket client;
Handler handler = new Handler();
WifiManager wmanager;
Boolean Alive;
DataOutputStream out;
DataInputStream in;
Button button_sent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helper);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
#SuppressWarnings("deprecation")
String ip = Formatter.formatIpAddress(wmanager.getConnectionInfo().getIpAddress());
smessage = (EditText) findViewById(R.id.smessage);
chat = (TextView) findViewById(R.id.chat);
display_status = (TextView) findViewById(R.id.display_status);
Thread serverThread = new Thread(new serverThread());
serverThread.start();
Alive = serverThread.isAlive();
display_status.setText("Hosted on: " + ip);
button_sent = (Button) findViewById(R.id.button_sent);
button_sent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
}
class sentMessage implements Runnable{
#Override
public void run() {
try{
client = serverSocket.accept();
out = new DataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
msg = msg+"\n Server:" +str;
handler.post(new Runnable()
{
#Override
public void run()
{
chat.setText(msg);
}
});
out.writeBytes(str);
out.flush();
out.close();
client.close();
}catch(IOException e){}
}
}
public class serverThread implements Runnable {
#Override
public void run() {
try {
while (true) {
serverSocket = new ServerSocket(serverport);
client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
display_status.setText("Connected");
}
});
/*******************************************
setup i/p streams
******************************************/
in = new DataInputStream(client.getInputStream());
String line = in.readUTF();
while (!line.equals("STOP")) {
msg = msg + "\n Client : " + line;
handler.post(new Runnable() {
#Override
public void run() {
chat.setText(msg);
}
});
}
in.close();
client.close();
}
} catch (Exception e) {
}
}
}
}
//#Client Side Java File
package reciever;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.*;
import java.net.*;
import inc.teckzy.wif_chat.R;
public class ClientSide extends AppCompatActivity {
EditText serverIp,smessage;
TextView chat;
String serverIpAddress = "",msg = "",str;
Handler handler = new Handler();
Button sent,connectPhones;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_side);
chat = (TextView) findViewById(R.id.chat);
serverIp = (EditText) findViewById(R.id.server_ip);
smessage = (EditText) findViewById(R.id.smessage);
sent = (Button) findViewById(R.id.sent_button);
connectPhones = (Button) findViewById(R.id.connect_phones);
//-----------------------Connecting to IP------------------------------//
connectPhones.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals(""))
{
Thread clientThread = new Thread(new
ClientThread());
clientThread.start();
}
}
});
//-------------------------------Initializing sent thread----------------//
sent.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Thread sentThread = new Thread(new sentMessage());
sentThread.start();
}
});
}
class sentMessage implements Runnable
{
#Override
public void run()
{
try
{
InetAddress serverAddr =
InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, 6666); //
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
str = smessage.getText().toString();
str = str + "\n";
msg = msg + "Client : " + str;
handler.post(new Runnable() {
#Override
public void run() {
chat.setText(msg);
}
});
os.writeUTF(str);
os.flush();
os.close();
socket.close();
}
catch(IOException e)
{
}
}
}
public class ClientThread implements Runnable
{
InetAddress serverAddr;
public void run()
{
try
{
while(true)
{
serverAddr = InetAddress.getByName(serverIpAddress);
Socket socket = new Socket(serverAddr, 6666);
/*******************************************
setup i/p streams
******************************************/
DataInputStream in = new
DataInputStream(socket.getInputStream());
String line = in.readUTF();
while (!line.equals("Stop"))
{
msg = msg + "Server : " + line + "\n";
handler.post(new Runnable()
{
#Override
public void run()
{
chat.setText(msg);
}
});
}
in.close();
socket.close();
Thread.sleep(100);
}
}
catch (Exception e)
{}
}
}
}
You are using client = serverSocket.accept(); in server side every time you need to send a message.
And in client side you are trying to create a new Socket connection using new Socket
(serverAddr, 6666); multiple times.
Maintain a single Socket connection and single data input/output stream(do not create multiple instances) and you will be good to go.
See example at:
https://github.com/nabinbhandari/android-socket-messaging
I Solved it Just deleted the "sentMessage" Thread and implemented output stream in "sent.setOnClickListener(new View.OnClickListener()" in both Activity also did some modifications..Here is the working code Activity ...Hope this will help someone
#Server Activity
package inc.teckzy.wifi_chat;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Helper extends AppCompatActivity {
EditText smessage;
TextView chat,display_status;
String str,Smsg,Cmsg="";
int serverport = 6666;
ServerSocket serverSocket;
Socket client;
Handler updateConversationHandler =new Handler();
WifiManager wmanager;
DataOutputStream out;
DataInputStream in;
Button button_sent;
StringWriter errors = new StringWriter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helper);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
#SuppressWarnings("deprecation")
String ip = Formatter.formatIpAddress(wmanager.getConnectionInfo().getIpAddress());
smessage = (EditText) findViewById(R.id.smessage);
chat = (TextView) findViewById(R.id.chat);
display_status = (TextView) findViewById(R.id.display_status);
Thread serverThread = new Thread(new serverThread());
serverThread.start();
display_status.setText("Hosted on: " + ip);
button_sent = (Button) findViewById(R.id.button_sent);
button_sent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
out = new DataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
Smsg = "Server:" + str;
updateConversationHandler.post(new updateUIThread(Smsg));
out.writeUTF(str);
out.flush();
}catch (Exception e) {
e.printStackTrace(new PrintWriter(errors));
updateConversationHandler.post(new updateUIThread(errors.toString()));
}
smessage.getText().clear();
}
});
}
public class serverThread implements Runnable {
#Override
public void run() {
try {
serverSocket = new ServerSocket(serverport);
while (true) {
client = serverSocket.accept();
updateConversationHandler.post(new updateUIThread("Connected"));
/*******************************************
setup i/p streams
******************************************/
in = new DataInputStream(client.getInputStream());
String line = "";
while (!line.equals("STOP")) {
line=in.readUTF();
Cmsg ="Client: "+ line;
updateConversationHandler.post(new updateUIThread(Cmsg));
}
in.close();
client.close();
}
} catch (Exception e) {
e.printStackTrace(new PrintWriter(errors));
updateConversationHandler.post(new updateUIThread(errors.toString()));
}
}
}
class updateUIThread implements Runnable {
private String msg;
updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
chat.setText(chat.getText().toString()+ msg + "\n");
}
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And
#Client Activity
package inc.teckzy.wifi_chat.reciever;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.Socket;
import inc.teckzy.wifi_chat.R;
public class ClientSide extends AppCompatActivity {
EditText serverIp,smessage;
TextView chat;
String serverIpAddress = "",Smsg,Cmsg = "",str;
Handler updateConversationHandler = new Handler();
Button sent,connectPhones;
Socket socket;
DataInputStream in;
DataOutputStream out;
StringWriter errors = new StringWriter();
WifiManager wmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_side);
chat = (TextView) findViewById(R.id.chat);
serverIp = (EditText) findViewById(R.id.server_ip);
wmanager = (WifiManager) getSystemService(WIFI_SERVICE);
smessage = (EditText) findViewById(R.id.smessage);
sent = (Button) findViewById(R.id.sent_button);
connectPhones = (Button) findViewById(R.id.connect_phones);
//-----------------------Connecting to IP------------------------------//
connectPhones.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals(""))
{
Thread clientThread = new Thread(new
ClientThread());
clientThread.start();
}
}
});
//-------------------------------Initializing sent thread----------------//
sent.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try {
out = new DataOutputStream(socket.getOutputStream());
str = smessage.getText().toString();
Cmsg = "Client: " + str;
updateConversationHandler.post(new updateUIThread(Cmsg));
out.writeUTF(str);
out.flush();
}catch(Exception e){
e.printStackTrace(new PrintWriter(errors));
updateConversationHandler.post(new updateUIThread(errors.toString()));}
smessage.getText().clear();
}
});
}
public class ClientThread implements Runnable
{
InetAddress serverAddr;
public void run()
{
try
{
serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, 6666);
updateConversationHandler.post(new updateUIThread("Connected"));
String ip = socket.getRemoteSocketAddress().toString();
updateConversationHandler.post(new updateUIThread(ip));
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
/*******************************************
setup i/p streams
******************************************/
String line = "";
while (!line.equals("Stop")) {
line=in.readUTF();
Smsg ="Server: " + line + "\n";
updateConversationHandler.post(new updateUIThread(Smsg));
}
out.close();
in.close();
socket.close();
}
catch (IOException e)
{updateConversationHandler.post(new updateUIThread("IO Error"));}
}
}
class updateUIThread implements Runnable {
private String msg;
updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
chat.setText(chat.getText().toString()+ msg + "\n");
}
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
#TargetApi(18)
public class MainActivity extends AppCompatActivity{
`int b = 0;
BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
BluetoothSocket BS;
BluetoothServerSocket server;
UUID uuid = UUID.fromString("f63b93f5-56e0-47bb-8972-996e34cfb9a8");`
`#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);`
`Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);`
`Accept accept = new Accept();
accept.start();`
Set<BluetoothDevice> devices = BA.getBondedDevices();
for(BluetoothDevice bt : devices) {
try {
if (bt.getName().equals("Overlord")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
} else if (bt.getName().equals("Huawei Y5")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
}
}catch(IOException IOE){}
}
}
public interface MessageContents{
int MSG_MESSAGE = 0;
}
Handler handler = new Handler(){
public void handleMessage(Message msg) {
TextView tx = (TextView)findViewById(R.id.textView2);
switch(msg.what){
case MessageContents.MSG_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d("TAG", readMessage);
tx.setText(readMessage);
break;
default:
tx.setText("No text");
}
}
};
class Connect extends Thread{
public void run(){
try {
try {
BS.connect();
Log.d("LOG", " e");
Log.d("LOG", "r" + BS.isConnected());
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.start();
}catch(NullPointerException e){
Log.d("LOG", " meezaan");
}
}catch(IOException e){
Log.d("LOG", "t");
}
}
}
class Accept extends Thread{
public void run() {
try {
while (true) {
server = BA.listenUsingRfcommWithServiceRecord("Secure Connection", uuid);
server.accept();
Log.d("LOG", "accept");
}
}catch(IOException E) {
}
}
}
class DataTransfer extends Thread{
#Override
public void run() {
int d = 1;
InputStream receive = null;
Log.d("LOG", "On");
int numBytes;
byte[] buffer = new byte[1024];
try {
receive = BS.getInputStream();
Log.d("LOG", "pn");
while (BS.isConnected()) {
try {
if (d <= 5) {
Log.d("LOG", "did");
++d;
}
numBytes = receive.read(buffer);
handler.obtainMessage(MessageContents.MSG_MESSAGE, numBytes, -1, buffer).sendToTarget();
} catch (NullPointerException e) {
Log.d("LOG", "error read(null)");
}
}
Log.d("LOG", "pnA");
} catch (IOException IOE) {
Log.d("LOG", "error read(IOE)");
}
}
}
public void onOne(View view){
write("1".getBytes());
}
public void onClick(View view){
Button b1 = (Button) findViewById(R.id.button);
EditText pin = (EditText) findViewById(R.id.editText);
pin.setRawInputType(Configuration.KEYBOARD_QWERTY);
pin.setVisibility(View.VISIBLE);
b1.setVisibility(View.VISIBLE);
}
public void pin (View view) {
Button b1 = (Button)findViewById(R.id.button);
EditText pin = (EditText)findViewById(R.id.editText);
String pin1 = pin.getText().toString();
if (pin1.equals("")) {
Connect connect = new Connect();
connect.run();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(getApplicationContext(), "Wrong Pin!"+pin1, Toast.LENGTH_SHORT).show();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
}
}
public void onTwo(View v){
Toast.makeText(getApplicationContext(), "" + handler.hasMessages(MessageContents.MSG_MESSAGE) + " " + BS.isConnected(), Toast.LENGTH_SHORT).show();
}
public void write(byte[] Byte){
try {
OutputStream transfer = BS.getOutputStream();
try {
transfer.write(Byte);
}catch(NullPointerException e){
Log.d("LOG", "error write(null) " + BS.isConnected());}
}catch (IOException IOE){ Log.d("LOG", "b");
Log.d("LOG", "error write(IOE) " + BS.isConnected());}
}
}`
Hi, this is my code. After writing Bytes[] I don't receive anything on second device. When I remove 'numBytes = receive.read(buffer)' handler would work or display
'no text'
I think receive.read(buffer) waits for an input which means write is a problem or receive.read(buffer) is the problem. Please ignore names, logs with random letters in or device names or unnecessary imports or variables. Thank You :) Sorry I did not have time to indent everything. If you are viewing please put something like don't know.Thank you.
i started with android a short time ago. This time i tried to connect a c# tcp server with a java tcp client. To debug i worte a c# client and server and if i use the c# client to talk to the server, there is no problem. But my java socket has problems with connecting. I copied the java tcp code for example from the net.
c# code:
namespace MTCliserv2
{
class MTCliserv2
{
static void Main(string[] args)
{
string txt;
Console.Write("MTCliserv2 Server or Client (s/c): ");
txt = Console.ReadLine();
if (txt == "s")
Server();
else
Client();
Console.Write("\nHit any Key to continue "); Console.ReadKey();
}
static IPAddress GetIPAddress()
{
IPAddress ipAdr = Dns.Resolve("localhost").AddressList[0];
ipAdr = IPAddress.Parse("192.168.1.1");
return ipAdr;
}
static void Server()
{
TcpListener server;
Socket socke;
IPAddress ipAdr = GetIPAddress();
try
{
server = new TcpListener(ipAdr, 13);
server.Start();
Console.WriteLine("Server {0} gestartet", server.LocalEndpoint);
while (true)
{
socke = server.AcceptSocket(); // Aufruf blockiert!!
mit diesem Client abwickelt
new ConnTalk(socke);
}
}
catch (Exception e)
{
Console.WriteLine("Error {0}", e);
}
}
static void PrintConnectionInfo(Socket aSock)
{
Console.WriteLine("Anfrage von {0}", aSock.RemoteEndPoint);
}
static void Client()
{
const string serverName = "localhost";
try
{
TcpClient client = new TcpClient("192.168.1.1", 13);
NetworkStream strm = client.GetStream();
Socket sc = client.Client;
StreamReader strmRd = new StreamReader(strm);
StreamWriter strmWr = new StreamWriter(strm);
string txt, txt2;
Console.WriteLine("Connected to {0}", sc.RemoteEndPoint);
while (true)
{
Console.Write("Msg= ");
txt = Console.ReadLine();
if (txt == "end")
break;
strmWr.WriteLine(txt); strmWr.Flush();
txt2 = strmRd.ReadLine();
Console.WriteLine("Answer: {0}", txt2);
}
client.Close(); strmRd.Close(); strmWr.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
// Pro Verbindung wird 1 ConnTalk-objekt erzeugt
class ConnTalk
{
Thread m_Thr;
Socket m_Sc;
public ConnTalk(Socket aSc)
{
m_Sc = aSc;
m_Thr = new Thread(this.TalkWithClient);
m_Thr.Start();
}
void TalkWithClient()
{
NetworkStream strm = new NetworkStream(m_Sc);
StreamReader strmRd = new StreamReader(strm);
StreamWriter strmWr = new StreamWriter(strm);
string txt;
Console.WriteLine("Talking with {0}", m_Sc.RemoteEndPoint);
try
{
while (true)
{
txt = strmRd.ReadLine();
Console.WriteLine("Msg: {0}", txt);
txt += " Echo!! \r\n";
strmWr.Write(txt); strmWr.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in TalkWithClient");
}
Console.WriteLine("{0} Disconnected", m_Sc.RemoteEndPoint);
m_Sc.Close(); strm.Close(); strmRd.Close(); strmWr.Close();
return;
}
}
}
And here is the java code:
package com.example.mogri.tcpsocket;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText ettext;
private TextView tvlog;
TcpClient mTcpClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ( ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.INTERNET},225);
}
if ( ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE},225);
}
ettext = (EditText) findViewById(R.id.etText);
tvlog = (TextView) findViewById(R.id.tVlog);
Button btnsend = (Button) findViewById(R.id.btnsend);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = ettext.getText().toString();
mTcpClient.sendMessage(input);
log(input);
}
});
new ConnectTask().execute("");
}
public void log(String add){
tvlog.setText( tvlog.getText()+"\n"+add);
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//response received from server
Log.d("test", "response " + values[0]);
//process server response here....
}
}
}
The tcpclient class:
package com.example.mogri.tcpsocket;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Created by mogri on 01.04.2017.
*/
public class TcpClient {
public static final String SERVER_IP = "192.168.1.1"; //server IP address
public static final int SERVER_PORT = 13;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
public TcpClient(OnMessageReceived listener) {
mMessageListener = listener;
}
public void sendMessage(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
mRun = false;
if (mBufferOut != null) {
mBufferOut.flush();
mBufferOut.close();
}
mMessageListener = null;
mBufferIn = null;
mBufferOut = null;
mServerMessage = null;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
//receives the message which the server sends back
mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
mServerMessage = mBufferIn.readLine();
if (mServerMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(mServerMessage);
}
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
Was trying to make a simple application that receives text from speech API and send it over to a java server.Tried debugging from traces. The code does not go beyond TRY block where i opened my socket.
Code Updated : Now the application is not crashing.But no message flow.
package info.androidhive.speechtotext;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.sql.DriverManager.println;
public class MainActivity extends Activity {
/**
* Declarations
*/
private TextView txtSpeechInput;
private ImageButton btnSpeak;
String str;
private final int REQ_CODE_SPEECH_INPUT = 100;
private String serverIpAddress = "";
private boolean connected = false;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
str = result.get(0);
setContentView(R.layout.activity_main);
Log.d("1- naval", " client oncreate");
Button button = (Button) findViewById(R.id.send);
textIn = (TextView) findViewById(R.id.textin);
/**
* Setting the text box with default value
*/
textIn.setText(str);
Log.d("settext", " 2-naval");
/**
* Here we need to fill in textin from MainActivity,
* where we received the speech API text
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!connected) {
serverIpAddress = "192.168.0.4";
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
}
);
}
}
}
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8888);
PrintWriter out = null;
out.println(str);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
// 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) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Since, at the time of writing this answer, the author has yet to add a stacktrace I'll go over some basic solutions:
Make sure you've added INTERNET permission to your android manifest, otherwise your socket wont open <uses-permission android:name="android.permission.INTERNET" />
Open your socket on a background thread. Networking on the UI thread (eg. inside the onClick method) is prohibited on android
Add a stack trace if the above didn't solve your problem