Why the Android TCP Client is not working? - java

I'm developing an apllication on Android Studio, which has the job of send an string to an C# TCP server on my computer.
My android app has the following code:
public void Send_Command(View v) {
testClass();
Toast.makeText(getApplicationContext(), "Comando Enviado!", Toast.LENGTH_LONG).show();
}
public static void testClass() {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
public static class ClientThread implements Runnable {
String results = "";
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
System.out.println("C: Connecting...");
while (true) {
results = "";
try {
Socket socket = new Socket("192.168.1.77", 8888);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Test");
out.flush();
String inMsg = "";
boolean b = false;
while (!b) {
inMsg = in .readLine();
if (inMsg != "")
b = true;
}
socket.close();
System.out.println("C: Closed.");
} catch (Exception e) {
System.out.println("S: Error" + e.toString());
}
}
} catch (Exception e) {
System.out.println("C: Error" + e);
}
}
}
I put the Send_Message on the onClick of a button and when I execute the app with the C# server on my PC, nothing happends, however, if I execute the same code that I have on android studio on Ecplipse, the string is sended.
I don't have many experience on Android Studio, so, perhaps I am commiting an stupid mistake, however, I don't know where.
Anyone know where the problem might be ?
Thanks

Related

How would I send a username/password from a Socket-run Java Client to a Server, verify the details, and then send a boolean result back to the client?

I've been working on a university project for a bit where I essentially coded a GUI along with a few other features on it. Recently, we've been tasked with implementing a server/client communication on the application, and the topic hasn't really been explained very well to us so I have been struggling. My idea for the implementation is to take the username & password that the client provides at the login screen, send it to a Server class, verify the details, and then send a boolean value of either true or false, depending on whether or not they have the correct details. This hasn't worked, and I don't believe the username/password test variables in the server class take on any values. I will share the relevant snippets of code from both the Client & Server class down below.
Client Part:
private void loginMessage() {
/*
* This is the default login message that will be displayed. We could add
* checkers and such to the information we receive from the username/password
* fields, however that is outside of the scope of our current homework
* assignment. I did, however, make sure to store the username in a string and
* personalize the welcome message.
*/
String uName = txtUsername.getText();
try {
dout.writeUTF(uName);
} catch (Exception e) {
}
String password = new String(usPassword.getPassword());
try {
dout.writeUTF(password);
} catch (Exception e) {
}
try {
boolean loginSuccess = din.readBoolean();
if (loginSuccess) {
JOptionPane.showMessageDialog(this,
"Thank you for logging in " + uName
+ ". You will now get redirected to our Customer Zone, where you can make purchases. Press OK to continue.",
"Success!", JOptionPane.INFORMATION_MESSAGE);
finished = true;
} else {
JOptionPane.showMessageDialog(this,
"Error. Either your username or password is incorrect. Please try again.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
}
}
private void cancel() {
/*
* This is the cancel operation. We will close the application when the cancel
* option is selected.
*/
System.exit(1);
}
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 7000);
InputStream in = socket.getInputStream();
DataInputStream din = new DataInputStream(in);
// send a message from client to server
OutputStream out = socket.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
} catch (Exception e) {
}
// We define a new MyApplication object in order to run our application.
MyApplication x = new MyApplication();
Progress a = new Progress();
Secondpage s = new Secondpage();
Thread t1 = new Thread(x);
t1.start();
try {
t1.join();
} catch (Exception e) {
e.printStackTrace();
}
a.start();
try {
a.join();
} catch (Exception e) {
e.printStackTrace();
}
s.start();
try {
s.join();
} catch (Exception e) {
e.printStackTrace();
}
}
Server Part:
public class MyServer {
Socket serverSocket;
BufferedReader br;
FileReader fr;
static String uname;
static String pwd;
static String filepath = "login.txt";
static String sep = ",";
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(7000);
System.out.println("Waiting for a client...");
Socket mySocket = serverSocket.accept();
System.out.println("I have a client");
DataInputStream clientIn = new DataInputStream(mySocket.getInputStream());
DataOutputStream clientOut = new DataOutputStream(mySocket.getOutputStream());
uname = clientIn.readUTF();
pwd = clientIn.readUTF();
System.out.println("I have a username " + uname + pwd);
boolean verif = verifyUserLogin(uname, pwd, filepath, sep);
clientOut.writeBoolean(verif);
System.out.println("Username: " + uname);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static boolean verifyUserLogin(String user, String pwd, String fp, String sep) {
String currentLine;
String data[];
try {
// We use FileReader to read file, and BufferedReader to read character stream.
FileReader fr = new FileReader(fp);
try (BufferedReader br = new BufferedReader(fr)) {
while ((currentLine = br.readLine()) != null) {
data = currentLine.split(sep);
if (data[0].equals(user) && data[1].equals(pwd)) {
return true;
}
}
}
} catch (Exception e) {
}
return false;
}
}
Now, my issue is I am struggling with sending the login and password strings over to the server. I don't think the username & password variables in the Server class are even holding any values to be honest, and I am unsure of how to fix this. I'm kind of lost, and really need some help. Thank you very much :)

Can I connect 2-computers using sockets in java?

Is it possible to write a client-server code that can connect 2-different computers to play a multi-player game using sockets in java? Do these computers need to be connected by a cable? Or can I send the data through some other source? (Like internet..) Or is it enough if I know just the ip addresses of both computers and put that in in the sockets? Please tell me how I can do it.
You can connect computers that are on the same Wifi network. You will need to open a server and then open clients that connect to it.
The following code may help:
Server.java
ArrayList<Socket> clientSockets = new ArrayList<>();
try {
ServerSocket serverSocket = new ServerSocket(port); // port same as client
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("Server opened at: "+inetAddress.getHostAddress());
while (true) // this keeps the server listening
{
final Socket socket = serverSocket.accept(); // this accepts incomming connections
clientSockets.add(socket); // adds current connection to an arraylist
System.out.println(timestamp()+"Connection from "+socket.getInetAddress());
Thread t = new Thread(new Runnable() // Thread handles messages sent by client that just connected
{
#Override
public void run() {
try
{
while (socket.isConnected())
{
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String fromClient = br.readLine();
if (fromClient != null)
{
//use message from client
}
else // connection might have been reset by client
{
socket.close();
clientSockets.remove(socket);
}
}
} catch (SocketException e)
{
System.out.println("Disconnection from "+socket.getInetAddress());
} catch (IOException e) {}
}
});
t.start();
}
} catch (Exception e) {}
Client.java - add two buttons, one for connecting and one for sending
bConnect.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
InetAddress address = InetAddress.getByName(host); // host IPaddress
socket = new Socket(address, port); // port same as server
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
final Timer time = new Timer(); // to get new server txt if it changes
TimerTask t = new TimerTask() {
#Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String kry = br.readLine();
// use message from server
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "The Server has just gone offline");
}
}
};
time.scheduleAtFixedRate(t, 0, 2000);
}
catch (Exception e1)
{e1.printStackTrace();
JOptionPane.showMessageDialog(null, "The Server is not online");}
}
});
bSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String textGekry = "what you are sending";
if (!textGekry.equals(""))
{
String sendMessage = textGekry + "\n";
try
{
bw.write(sendMessage);
bw.flush();
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(null,"The Server is most likely offline");
}
}
}
});

Android - PC usb connection - do it without wifi

I wanted to ask how to change following code, which needs USB connection and WIFI to work... (and I don't know why wifi...), to code, which needs only USB cable and NO WIFI!, because I don't want to be dependent on wifi...
Could you please help me? Some changes or additions in code? Thanks.
Code for Android:
private final Runnable connectToServer = new Thread()
{
#Override
public void run()
{
try
{// Get the server address from a dialog box.
String serverAddress = "192.168.0.23";
// Make connection and initialize streams
Socket socket = new Socket(serverAddress, 38300);
in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Consume the initial welcoming messages from the server
for (int i = 0; i < 3; i++) {
System.out.println(in.readLine());
}
solveCube();
} catch (IOException e) {
e.printStackTrace();
}
}
};
private final Runnable initializeConnection = new Thread()
{
#Override
public void run()
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(generateCubeString());
out.println(generateCubeString());
String response ="";
try {
response = in.readLine();
if (response == null || response.equals("")) {
System.exit(0);
}
} catch (IOException ex) {
}
if (response.contains("Error")) {
} else {
solveCubeAnimate(response);
}
System.out.println(response);
final String finalResponse = response;
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(finalResponse);
}
});
}
};
Code for PC
private static class Capitalizer extends Thread {
private Socket socket;
private int clientNumber;
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
/**
* Services this thread's client by first sending the
* client a welcome message then repeatedly reading strings
* and sending back the capitalized version of the string.
*/
public void run() {
try {
// Decorate the streams so we can send characters
// and not just bytes. Ensure output is flushed
// after every newline.
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a welcome message to the client.
out.println("Hello, you are client #" + clientNumber + ".");
out.println("Enter a line with only a period to quit\n");
// Get messages from the client, line by line; return them
// capitalized
while (true) {
String input = in.readLine();
if (input == null || input.equals(".")) {
break;
}
out.println(solveCube(input));
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
}
/**
* Logs a simple message. In this case we just write the
* message to the server applications standard output.
*/
private void log(String message) {
System.out.println(message);
}
}
private static class Connecter extends Thread {
/**
* Services this thread's client by first sending the
* client a welcome message then repeatedly reading strings
* and sending back the capitalized version of the string.
*/
public void run() {
try {
System.out.println("The capitalization server is running.");
int clientNumber = 0;
ServerSocket listener = new ServerSocket(38300);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Socket Issue - Only first message read

I am very new to sockets and was hoping someone could help me. I had something working but it was not sending information very quickly so i have refactored and now cannot get back to anything which works. The issue seems to be that only the first message that is published is read and then the receiver sits on client = listener.accept(); even though im pretty sure the sender is still sending messages
Can anyone see what i might be doing wrong here please?
Thanks
public class Sender {
Socket server = null;
DataInputStream inp = null;
PrintStream outp = null;
public Sender(){
server = new Socket("127.0.0.1" , 3456);
outp = new PrintStream(server.getOutputStream());
}
private void connectAndSendToServer(String message) {
outp = new PrintStream(server.getOutputStream());
outp.print(message + "\n");
outp.flush();
}
}
Receiver class
public class Receive{
public String receiveMessage(int port) {
String message= null;
ServerSocket listener = null;
Socket client = null;
try{
listener = new ServerSocket(port);
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
return br.readLine();
}
...
finally{
try {
if(client!=null && listener!=null){
client.close();
listener.close();
}
}
catch (IOException e) {
}
}
return message;
}
}
This because a ServerSocket is used as an entry point for a normal Socket. accept() is a blocking operation that is usually done on a different thread compared to the one that receives/sends data to normal Socket. It sits there and waits for a new connection to spawn a new Socket which is then used for data.
This means that while receiving messages you should call just readLine() to read from the specific Socket. Having an accept inside the receiveMessage is wrong just because it's a different operation and it's even blocking.
Socket socket = serverSocket.accept();
ClientThread thread = new ClientThread(socket);
class ClientThread extends Thread {
Socket socket;
public void run() {
while (!closed) {
String line = reader.readLine();
...
}
}
You don't need to have a thread for every client though, but you need at least two for sure if you want to make your server accept a number of connections greater than 1.
You are not using ServerSocket correctly. You shouldn't create a new instance for every message but use it as a data member maybe and run an infinite loop to get a new client socket connection. Because you create it locally, the socket is closed since the object is no longer used and referenced (and so GC'ed), when you return from the method.
Something like (< condition met > is pseudo-code defines your condition to accept new connections):
while(< condition met >) {
try {
client = listener.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = br.readLine();
//do something with str
} finally {
//close client socket
}
}
Better approach will be to handle client socket in a different thread so the main thread is back to accept while you can do anything with the client socket in parallel.
Try this basic Chatting Server written by me. This server simply keeps running in loop and broadcast the message send by the clients to all the other clients associated with this server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
// ///----------------------------------------Instance Variable Fields
ServerSocket ss = null;
Socket incoming = null;
// ///----------------------------------------Instance Variable Fields
// ///---------------------------------------- static Variable Fields
public static ArrayList<Socket> socList = new ArrayList<Socket>();
// ///---------------------------------------- static Variable Fields
public void go() {
try {
ss = new ServerSocket(25005);
while (true) {
incoming = ss.accept();
socList.add(incoming);
System.out.println("Incoming: " + incoming);
new Thread(new ClientHandleKaro(incoming)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandleKaro implements Runnable {
InputStream is = null;
OutputStream os = null;
InputStreamReader isr = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean isDone = false;
Socket sInThread = null;
public ClientHandleKaro(Socket sxxx) {
this.sInThread = sxxx;
}
#Override
public void run() {
if (sInThread.isConnected()) {
System.out.println("Welcamu Clienta");
System.out.println(socList);
}
try {
is = sInThread.getInputStream();
System.out.println("IS: " + is);
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = sInThread.getOutputStream();
pw = new PrintWriter(os, true);
String s = new String();
while ((!isDone) && (s = br.readLine()) != null) {
String[] asx = s.split("-");
System.out.println("On Console: " + s);
// pw.println(s);
Thread tx = new Thread(new ReplyKaroToClient(s,
this.sInThread));
tx.start();
if (asx[1].trim().equalsIgnoreCase("BYE")) {
System.out.println("I am inside Bye");
isDone = true;
}
}
} catch (IOException e) {
System.out.println("Thanks for Chatting.....");
} finally {
try {
Thread tiku = new Thread(new ByeByeKarDo(sInThread));
tiku.start();
try {
tiku.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Accha to hum Chalte hain !!!");
System.out.println(socList);
br.close();
pw.close();
sInThread.close();
} catch (IOException e) {
}
}
}
}
class ReplyKaroToClient implements Runnable {
public String mString;
public Socket mSocket;
public ReplyKaroToClient(String s, Socket sIn) {
this.mString = s;
this.mSocket = sIn;
}
#Override
public void run() {
for (Socket sRaW : socList) {
if (mSocket.equals(sRaW)) {
System.out.println("Mai same hun");
continue;
} else {
try {
new PrintWriter(sRaW.getOutputStream(), true)
.println(mString);
} catch (IOException e) {
System.out.println("Its in Catch");
}
}
}
}
}
class ByeByeKarDo implements Runnable {
Socket inCom;
public ByeByeKarDo(Socket si) {
this.inCom = si;
}
#Override
public void run() {
try {
new PrintWriter(inCom.getOutputStream(), true)
.println("You have Logged Out of Server... Thanks for your Visit");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server().go();
}
}

sending packet over 3G network

I am trying to write a method that will send a message over a 3G network with a base station to the server. IM trying to send the message multiple times until I decide to stop. But when I tested this, it always stops after a short time and stops sending the message. Anyone know why?
private Runnable commRunnable = new Runnable() {
public void run() {
try {
String message = "Just saying hello!";
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true);
String startReceivingMessage = "Begin sending me data.";
String stopReceivingMessage = "Stop sending me data.";
startSend = false;
stopSend = false;
startReceive = false;
stopReceive = false;
while (!shouldDisconnect) {
if (startSend) {
sendData = true;
startSend = false;
}
if (stopSend) {
sendData = false;
stopSend = false;
}
// Send a message that the server should start transmitting data
// back to us. We only need to transmit this message once.
if (startReceive) {
out.println(startReceivingMessage);
startReceive = false;
receiveData = true;
Thread receiveThread = new Thread(receiveRunnable);
receiveThread.start();
// Tell the server to stop transmitting data.
} else if (stopReceive) {
out.println(stopReceivingMessage);
stopReceive = false;
receiveData = false;
}
if (sendData) {
out.println(message);
}
Thread.sleep(20);
}
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
} finally {
try {
socket.close();
connected = false;
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
}
}
}
};
private Runnable receiveRunnable = new Runnable() {
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String reply = "";
Log.d("PowerMonitor", "Starting to receive");
while (receiveData) {
Log.d("PowerMonitor", "Listening...");
reply = in.readLine();
Log.d("PowerMonitor", "Got message: " + reply);
}
} catch (Exception e) {
Log.e("PowerMonitor", e.toString());
}
}
};
We need more of your code for better understanding of your question, but from the code you posted here its seems like the socket is being closed by the
socket.close();
call in the finally block.
Also tell about any errors you are getting.

Categories

Resources