So I have this really, really strange problem with getting data using socket from server which is working on my PC to Android app. All in local network for now.
It is strange, because I wrote server and client apps (both using sockets) to send and get data and it works really great. I tried to do exactly the same on Android and it gets only first response from server, but not the rest after sending token.
I searched through SO and saw piece of advice that available() method is not right so I changed it and it's still not working as I wish it would.
I think there is something wrong with server-side app or android app works way too fast for server and it sends data after ending transmission on android, but I tried to give it a bit of time and nothing...
This is server app (in general it gets token, lets say "RAM" then it gets output from linux process and sends it straight to android app):
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
public class BLCServer extends Thread{
private ServerSocket serverSocket;
public BLCServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(86400000);
}
public void run() {
while(true) {
try {
String token = "";
System.out.println("Waiting for a client on port: "+serverSocket.getLocalPort());
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
System.out.println("Beginning transmission");
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thanks for connecting to " + server.getLocalSocketAddress() + "Goodbye\n");
while(token != "END") {
token = in.readUTF();
if(token.equals("RAM")) {
Ram ram = new Ram();
List<String> ramData = new ArrayList<>();
ramData = ram.getRamData();
System.out.println("RAM");
System.out.println("ram.size(): " + ramData.size());
out.writeUTF("ramBeginning");
for(String x : ramData) {
System.out.println("Wysyłam do clienta: " + x);
out.writeUTF(""+x);
}
out.writeUTF("ramEnd");
} else if(token.equals("CPU")) {
Cpu cpu = new Cpu();
List<String> cpuData = new ArrayList<>();
cpuData = cpu.getCpuLoad();
System.out.println("CPU");
out.writeUTF("cpuBeginning");
for(String x : cpuData) {
out.writeUTF(x);
}
out.writeUTF("cpuEnd");
} else if(token.equals("STORAGE")) {
Storage storage = new Storage();
List<String> storageData = new ArrayList<>();
storageData = storage.printStorageData();
System.out.println("STORAGE");
out.writeUTF("storageBeginning");
for(String x : storageData) {
out.writeUTF(x);
}
out.writeUTF("storageEnd");
} else if(token.equals("UPTIME")) {
Uptime uptime = new Uptime();
String uptimeData = uptime.getUptime();
System.out.println("UPTIME");
out.writeUTF("uptimeBeginning");
out.writeUTF(uptimeData);
out.writeUTF("uptimeEnd");
} else if(token.equals("TEMPERATURES")) {
out.writeUTF("temperaturesBeginning");
out.writeUTF("temperaturesEnd");
} else if(token.equals("END")) {
break;
} else {
out.writeUTF("Token unknown");
}
}
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = 1984;
try {
Thread t = new BLCServer(port);
t.start();
} catch(IOException e) {
e.printStackTrace();
}
}
}
And also there is android main activity:
public class MyActivity extends Activity {
TextView cpuT;
TextView ramT;
TextView uptimeT;
TextView storageT;
List<String> ram = new ArrayList<String>();
List<String> cpu = new ArrayList<String>();
List<String> uptime = new ArrayList<String>();
List<String> storage = new ArrayList<String>();
List<String> temperatures = new ArrayList<String>();
public class NetThread extends AsyncTask<String, Void, Void> {
String dstAddress = "192.168.0.111";
int dstPort = 1984;
#Override
protected Void doInBackground(String... args) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
InputStream inFromServer = new PushbackInputStream(socket.getInputStream());
DataInputStream in = new DataInputStream(inFromServer);
out.writeUTF("Hello from " + socket.getLocalSocketAddress());
int singleByte;
ramT.setText(in.readUTF());
out.writeUTF("RAM");
while((singleByte = inFromServer.read()) != -1) { // there was code like: while(in.available() > 0) { ... } but someone wrote about it's bad behaviour on SO
ramT.setText(ramT.getText() + "\n" + singleByte);
}
}
out.writeUTF("END");
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("WEBSERVICE", "Oncreate wywołane\n");
cpuT = (TextView) findViewById(R.id.displayCpu);
ramT = (TextView) findViewById(R.id.displayRam);
uptimeT = (TextView) findViewById(R.id.displayUptime);
storageT = (TextView) findViewById(R.id.displayStorage);
NetThread netThread = new NetThread();
netThread.execute("RAM", "STORAGE", "UPTIME");
}
}
In addition I paste you client application for pc:
public class BLCClient {
public static void main(String[] args) {
String serverName = "localhost";
int port = 1984;
try {
System.out.println("Connecting to..."+serverName+" on port 1984");
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "+client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
Scanner cin = new Scanner(System.in);
String token = "";
out.writeUTF("Hello from " + client.getLocalSocketAddress());
System.out.println("Server says: "+in.readUTF());
while(true) {
System.out.println("Podaj token ciulu: ");
token = cin.nextLine();
System.out.println("Twój token: " + token);
if(token.equals("END")) {
out.writeUTF(token);
break;
} else {
out.writeUTF(token);
System.out.println(in.readUTF());
System.out.println("IN: " + in.available());
while(in.available() > 0) {
System.out.println(in.readUTF());
}
}
}
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
Yes. I'm using part of code from tutorialspoint.com. If you need classes for getting data for ram, cpu, storage, temperatures or uptime processes let me know.
For now I've spent around 4 days trying to figure out what is wrong with my code for android (because servers sends data correctly, I'm 99% sure). Please help me. I'm powerless and I want this app wake to work so so badly right now (Actually I made this work using tomcat server, but I want my own server in here).
Thanks.
Related
I have a situation with a Java Socket Input reader.
I am trying to develop an URCAP for Universal Robots and for this I need to use JAVA.
The situation is as follow:
I connect to the Dashboard server through a socket on IP 127.0.0.1, and port 29999.
After that the server send me a message "Connected: Universal Robots Dashboard Server".
The next step I send the command "play".
Here starts the problem. If I leave it like this everything works.
If I want to read the reply from the server which is "Starting program" then everything is blocked.
I have tried the following:
-read straight from the input stream-no solution
-read from an buffered reader- no solution
-read into an byte array with an while loop-no solution
I have tried all of the solution presented here and again no solution for my case.
I have tried even copying some code from the Socket Test application and again no solution.
This is strange because as mentioned the Socket Test app is working with no issues.
Below is the link from the URCAP documentation:
https://www.universal-robots.com/articles/ur/dashboard-server-cb-series-port-29999/
I do not see any reason to post all the trials code because I have tried everything.
Below is the last variant of code maybe someone has an idea where I try to read from 2 different buffered readers. The numbers 1,2,3 are there just so I can see in the terminal where the code blocks.
In conclusion the question is: How I can read from a JAVA socket 2 times?
Thank you in advance!
public void sendPlay() {
try {
// Create a new Socket Client
Socket sc = new Socket("127.0.0.1", 29999);
if (sc.isConnected()) {
InputStream is = sc.getInputStream();
BufferedInputStream in = new BufferedInputStream(is);
String data = "";
int s = in.read();
data += ""+(char)s;
int len = in.available();
System.out.println("Len got : "+len);
if(len > 0) {
byte[] byteData = new byte[len];
in.read(byteData);
data += new String(byteData);
}
System.out.println(data);
System.out.println("1");
// Create stream for data
DataOutputStream out;
out = new DataOutputStream(sc.getOutputStream());
String command = new String();
command = "play"+"\n";
// Send command
out.write(command.getBytes("US-ASCII"));
out.flush();
System.out.println("2");
InputStream is1 = sc.getInputStream();
BufferedInputStream in1 = new BufferedInputStream(is1);
String data1 = "";
int s1 = in1.read();
data1 += ""+(char)s1;
int len1 = in1.available();
System.out.println("Len got : "+len1);
if(len1 > 0) {
byte[] byteData1 = new byte[len1];
in.read(byteData1);
data1 += new String(byteData1);
}
System.out.println(data1);
System.out.println("3");
// Perform housekeeping
out.close();
sc.close();
}
sc.close();
} catch (IOException e) {
System.out.println(e);
}
}
The problem seems to be that you are opening several input streams to the same socket for reading commands.
You should open one InputStream for reading, one OutputStream for writing, and keep them both open till the end of the connection to your robot.
Then you can wrap those streams into helper classes for your text-line based protocol like Scanner and PrintWriter.
Sample program to put you on track (can't test with your hardware so it might need little tweaks to work):
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class RobotTester implements AutoCloseable {
private Socket clientSocket;
private Scanner inputReader;
private PrintWriter outWriter;
private int incounter;
private int outcounter;
public static void main(String[] args) {
System.out.println("Program started. Connecting to robot");
try (RobotTester robot = new RobotTester("127.0.0.1", 29999)) {
System.out.println("Connected to robot.");
robot.nextInput(); //Read and print robot's welcome message
robot.writeCommand("play"); //Send command
String resp = robot.nextInput(); //Read result
if (resp.toLowerCase().startsWith("fail")) {
throw new Exception("Play command failed: " + resp);
}
System.out.println("Command succeeded!");
} catch (Throwable t) {
t.printStackTrace();
}
}
public RobotTester(String host, int port) throws UnknownHostException, IOException {
clientSocket = new Socket(host, port);
inputReader = new Scanner(clientSocket.getInputStream());
outWriter = new PrintWriter(clientSocket.getOutputStream());
}
public String nextInput() {
String mess = inputReader.nextLine();
System.out.println("< " + (++incounter) + ": " + mess);
return mess;
}
public void writeCommand(String command) {
System.out.println("> " + (++outcounter) + ": " + command);
outWriter.print(command);
outWriter.print('\n');
outWriter.flush();
}
#Override
public void close() throws Exception {
if (inputReader != null) {
inputReader.close();
inputReader = null;
}
if (outWriter != null) {
outWriter.close();
outWriter = null;
}
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
}
In addition, you're using 127.0.0.1 as server IP address, which is the loopback on your PC. Unless the interface to your robot works in a very peculiar way, the actual IP you should use is probably not this one.
I'm refering to this part of documentation here:
Setup a static IP-address and subnet mask on PC, so it matches the
robot, e.g.:
PC: IP-addr: 192.168.3.10 Robot: IP-addr: 192.168.3.3
Subnet: 255.255.255.0 Subnet: 255.255.255.0
Edit
If you've got more commands to put, use it like this:
//Inside your actual main class
public static void main(String[] args) {
System.out.println("Program started. Connecting to robot");
try (RobotTester robot = new RobotTester("127.0.0.1", 29999)) {
System.out.println("Connected to robot.");
robot.nextInput(); //Read and print robot's welcome message
robot.writeCommand("play"); //Send command
String resp = robot.nextInput(); //Read result
if (resp.toLowerCase().startsWith("fail")) {
throw new Exception("Play command failed: " + resp);
}
System.out.println("Command succeeded!");
robot.writeCommand("command1"); //Send command
resp = robot.nextInput(); //Read result
//Process result for command1
robot.writeCommand("command2"); //Send command
resp = robot.nextInput(); //Read result
//Process result for command2
//...
} catch (Throwable t) {
t.printStackTrace();
}
}
The latest update is that I have moved all the functions in the same Dialog and just called them straight from there, and is still not working.
I already double check there is just one stream and one writer and reader in the entire project.
JButton btnNewButton_2 = new JButton("START");
btnNewButton_2.setBackground(Color.GREEN);
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
RobotTester("127.0.0.1", 29999);
nextInput();
String command="play";
writeCommand(command);
nextInput();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} });
public void RobotTester(String host, int port) throws UnknownHostException, IOException {
clientSocket = new Socket(host, port);
inputReader = new Scanner(clientSocket.getInputStream());
outWriter = new PrintWriter(clientSocket.getOutputStream());
}
public String nextInput() {
String mess = inputReader.nextLine();
System.out.println("< " + (++incounter) + ": " + mess);
return mess;
}
public void writeCommand(String command) {
System.out.println("> " + (++outcounter) + ": " + command);
outWriter.print(command);
outWriter.print('\n');
outWriter.flush();
}
public void close() throws Exception {
if (inputReader != null) {
inputReader.close();
inputReader = null;
}
if (outWriter != null) {
outWriter.close();
outWriter = null;
}
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
I have found a solution to the issue of reading the from the socket multiple times with a Swing GUI.
public void sendPlay() {
Thread appThread = new Thread() {
public void run() {
try {
RobotTester robot = new RobotTester("127.0.0.1", 29999);
System.out.println("Connected to robot.");
robot.nextInput(); //Read and print robot's welcome message
robot.writeCommand("play"); //Send command
String resp = robot.nextInput(); //Read result
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Finished on " + Thread.currentThread());
}
};
appThread.start();}
It seems that the background socket reading needs to be on a separate thread. This was causing the entire robot to be blocked. The idea was from an forum. It was not mine, but hey, it works.
Thank you very much!
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
I am creating a Java file send program. Right now I am attempting to implement a chat messaging system.
Here is the code for calling the Server/Client code:
if(host.isSelected()) {
Server server = new Server();
ServerChat serverChat = new ServerChat();
server.Thread();
serverChat.Thread();
}
else if(guest.isSelected()) {
Client client = new Client();
ClientChat clientChat = new ClientChat();
client.Thread();
clientChat.Thread();
}
This calls the code in the following classes: ServerChat
public class ServerChat extends Main implements Runnable {
public static ServerSocket ss;
public static Socket s;
public static DataInputStream dis;
public static DataOutputStream dos;
public void Thread() {
(new Thread(new ServerChat())).start();
}
#Override
public void run() {
String variable = "";
try {
ss = new ServerSocket(1234);
s = ss.accept();
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
while (!variable.equals("exit")) {
variable = dis.readUTF();
chatText.setText(chatText.getText().trim() + "\n Client:\t" + variable);
}
} catch (Exception e) {
}
if (send.isSelected()) {
try {
String messageOut = "";
messageOut = chatText.getText().trim();
dos.writeUTF(messageOut);
} catch (Exception e) {
}
}
}
}
ClientChat code:
public class ClientChat extends Main implements Runnable {
public void Thread() {
(new Thread(new ClientChat())).start();
}
#Override
public void run() {
try {
socket = new Socket("localhost", 1234);
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
String variable = "";
while (!variable.equals("exit")) {
variable = dis.readUTF();
chatText.setText(chatText.getText().trim() + "\n Server:\t" + variable);
}
} catch (Exception e) {
}
if (send.isSelected()) {
try {
String messageOut = "";
messageOut = chatText.getText().trim();
dos.writeUTF(messageOut);
} catch (Exception e) {
}
}
}
}
They are able to connect to each other, but the data is not being posted into the text boxes which I have created in the main class. (All the elements needed from main are public).
When I connect (via locahost) I create the server through a new class and open up a new thread
public class Server extends Main implements Runnable {
public ServerSocket welcomeSocket;
public String file;
public DataOutputStream dos;
public DecimalFormat df = new DecimalFormat("##, #00");
public BufferedReader inFromClient;
public void Thread() {
(new Thread(new Server())).start();
}
#Override
public void run() {
try {
InetAddress localaddr = InetAddress.getLocalHost();
chatText.append("Local IP Address : " + localaddr);
chatText.append("Local hostname : " + localaddr.getHostName());
String clientSentence = null;
String capitalizedSentence;
welcomeSocket = new ServerSocket(1234);
String file = "";
DecimalFormat df = new DecimalFormat("##, #00");
while (true) {
Socket connectionSocket = welcomeSocket.accept();
inFromClient
= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
} catch (Exception e) {
chatText.append("Unable to create server");
chatText.append("Can't detect local host : " + e);
}
}
The Same goes for the Client:
public class Client implements Runnable {
public DataOutputStream dos;
public DataInputStream dis;
public Socket skt;
public StringTokenizer st;
public void Thread() {
try {
dos = new DataOutputStream(skt.getOutputStream());
dis = new DataInputStream(skt.getInputStream());
} catch (Exception e) {
System.out.println(e.getMessage());
}
(new Thread(new Client())).start();
}
#Override
public void run() {
try {
InetAddress localaddr = InetAddress.getLocalHost();
skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
while (!Thread.currentThread().isInterrupted()) {
String data = dis.readUTF();
st = new StringTokenizer(data);
String CMD = st.nextToken();
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File f = open.getSelectedFile();
String fileName = f.getAbsolutePath();
FileInputStream fs = new FileInputStream(fileName);
switch (CMD) {
case "CMD_SENDFILE":
try {
fileName = st.nextToken();
System.out.println("Receiving file...");
String path = System.getProperty("user.home");
File file = new File(path + "/Downloads" + fileName + ".txt");
FileOutputStream fos = new FileOutputStream(path);
InputStream input = skt.getInputStream();
byte[] buffer = new byte[1024];
int count, percent = 1;
while ((count = input.read(buffer)) > 0) {
percent = percent + 1;
fos.write(buffer, 0, count);
}
fos.close();
System.out.println("File was saved: " + path);
} catch (Exception e) {
DataOutputStream eDos = new DataOutputStream(skt.getOutputStream());
System.out.println(e.getMessage());
skt.close();
}
break;
}
}
/*String string = in.readLine();
System.out.println("Incoming: " + string + "\n");
System.out.println("Incoming: " + in.readLine() + "\n");
//in.close();*/
} catch (Exception e) {
System.out.println("Error could not connect\n");
}
}
}
Your main problem is here:
public class ClientChat extends Main implements Runnable {
You're mis-using inheritance. Inheritance is not used so that one instance can share variables with another, which is what you're trying to use it for. Instead it's mainly used to share behaviors. I strongly urge that ClientChat not extend Main but rather has a Main field, one whose public methods it can call.
Your other two problems are lesser problems, but they still will cause you headaches:
You generally want to avoid ignoring exceptions as you're doing. At least have the catch block print the stacktrace: e.printStackTrace();.
You will want to be sure that Swing calls, including calls to setText(...) on text components, be made on the Swing event thread. If you're using a plain vanilla thread, then this can be done via SwingUtilities.invokeLater(new Runnable() {...});. Otherwise consider using a SwingWorker which will help automate this for you with its publish / process method pair.
You've asked:
About inheritance, is there any post I can look at for calling main fields for the ClientChat?
Look up "inheritance vs composition" -- you would be using the latter, composition here, not inheritance.
You would likely want to pass information back and forth between the GUI, or "view" portion of your code, with the chat engine or "model" portion of your code. There are several ways to do that, but usually they'd be connected by some type of "control" class or classes, something known as the "MVC" or "Model-View-Controller" architecture.
I am trying to send an ArrayList to a client on an android device. The server says it sent the object however on the android device it hangs. I have read around that when creating an ObjectInputStream, an ObjectOuputStream must be created first and then flushed. I have tried that however this is not working for me. I didn't post the code for getting the clients as its just simply reading from a textfile. The Client class is very basic with few properties such as username, password and friends arraylist of strings. Any help would be much appreciated.
Server:
public class Server {
private static final int port = 9001;
private static final String IPAddr = "xxxxxxxxxxx";
ServerSocket server = null;
ArrayList <Client> users = new ArrayList<Client>();
public Server(){
try{
server = new ServerSocket(port);
System.out.println("connected server on port" + port);
while(true){
System.out.println("waiting for connection my ip add is "+ InetAddress.getLocalHost().getHostAddress());
Socket clientsocket = server.accept();
System.out.println("Connect to client:"+ clientsocket.getInetAddress().getHostName());
ClientThread client = new ClientThread(clientsocket);
client.start();
}
} catch(IOException e) {
System.err.println("Could not listen on port");
}
}
//Thread
public class ClientThread extends Thread {
private Socket sckt = null;
public ClientThread(Socket sckt){
super("ClientThread");
this.sckt = sckt;
}
public void run(){
try{
PrintWriter out = new PrintWriter(sckt.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
ObjectOutputStream objectOutput = new ObjectOutputStream(sckt.getOutputStream());
objectOutput.flush();
String Username = input.readLine();
String Password = input.readLine();
System.out.println("recieved from client: "+ Username);
int ClientIndex = isClient(Username);
if (ClientIndex != -1){
if(users.get(ClientIndex).password.equals(Password)){
//password correct -> send friends
out.println("correct");
out.flush();
System.out.println(Username + " is correct");
LoadClientFriends(Username, ClientIndex);
objectOutput.writeObject(users.get(ClientIndex).Friends);
System.out.println("Friends sent");
} else {
//password incorrect -> retry
out.println("password");
System.out.println(Username + " has wrong password");
}
} else {
//not a registered client
out.println("wrong");
System.out.println(Username + " is not a client");
}
} catch(Exception e){
System.err.println("Couldnt connect to Client socket");
}
}
}
public static void main(String[] args){
Server svr = new Server();
}
}
Client/Android:
public class MainActivity extends ActionBarActivity {
//Varibles
EditText username;
EditText password ;
private static final int port = 9001;
private static final String IPAddr = "xxxxxxx";
//Methods
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
/* Drawable d = getResources().getDrawable(R.drawable.actionbar_background);
getActionBar().setBackgroundDrawable(d);*/
}
public void Login(View view) {
//connect to server
Thread myThread2 = new Thread(Connect);
myThread2.start();
}
public void Register(View view) {
Intent i = new Intent(this, register_screen.class);
startActivity(i);
}
Runnable Connect = new Runnable()
{
public void run()
{
try {
Socket connection = new Socket(IPAddr,port);
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter output = new PrintWriter(connection.getOutputStream(), true);
//Sent the username a password for verifaction
username = (EditText)findViewById(R.id.edtName);
password = (EditText)findViewById(R.id.edtPassword);
output.println(username.getText().toString());
output.flush();
output.println(password.getText().toString());
output.flush();
//Receive confirmation of client
String res = input.readLine();
if (res.contains("correct")){
ObjectOutputStream objectOutput = new ObjectOutputStream(connection.getOutputStream());
objectOutput.flush();
ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(connection.getInputStream())); //Error Line!
Object object = objectInput.readObject();
ArrayList<String> friends = (ArrayList<String>) object;
Intent intent = new Intent(MainActivity.this,chat_screen.class);
intent.putExtra("Friends", friends);
startActivity(intent);
}else if (res.contains("password")){
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
}else {
}
}catch (Exception e){
}
}
};
}
The error you see is due to multiple output stream format. Stick to either ObjectOutputStream/ObjectInputStream or PrintWriter/BufferedReader. I suggest ObjectOutputStream/ObjectInputStream.
Server code: Use objectOutPut for all writes.
// out.println("correct");
objectOutput.writeUTF("correct");
// Update code for password and wrong too - Use objectOutput.writeUTF("");
Client code: Use just ObjectInputStream instead of BufferedReader
Define the objectInput here instead:
// BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ObjectInputStream objectInput = new ObjectInputStream(connection.getInputStream());
PrintWriter output = new PrintWriter(connection.getOutputStream(), true);
// Read data as follows:
// String res = input.readLine();
String res = objectInput.readUTF();
I'm trying to make a chat application in java, but I had a problem, when I couldn't send to another machine.
Here's part of my codes:
This is my class client:
public class EnvioSocket {
public static boolean enviarSocket(String nome, String ip, int porta,
String mensagem) {
String dados = nome + " : " + mensagem;
try {
Socket socket = new Socket(ip, porta);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(dados);
out.close();
socket.close();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
}
return true;
}
}
This is my class server:
public class ServidorThread implements Runnable {
private JTextArea menssage;
public ServidorThread(JTextArea menssage) {
this.menssage = menssage;
}
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(Porta.PORTA);
while (true) {
Socket acceptedSocket = serverSocket.accept();
DataInputStream in = new DataInputStream(
acceptedSocket.getInputStream());
String menssage = in.readUTF();
this.menssage.append(DateUtils.dateToString(new Date(), "dd/MM/yyyy HH:mm") + " " + menssage + "\n");
in.close();
acceptedSocket.close();
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
define a port to socket
public final class Porta {
private Porta() {
}
public static final int PORTA = 6066;
}
I can only send a message to my own computer. How can I fix this?
I'm starting my thread inside of my class that make a GUI.
It looks like you've set up your Server right, but your client doesn't seem to ever connect to it. You need to create a socket which will connect to the server socket. This socket can then give you I/O streams to send data through.
Java's tutorial, complete with code examples
The question is not that simple to me...I can show you the basics for client server echo application in java...You can expand on that to make a chat session between to clients I suppose...here it goes...
public class MultiThreadServer implements Runnable {
Socket csocket;
private static boolean quitFlag = false;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (!quitFlag) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
String action = in.readLine();
PrintStream pstream = new PrintStream(csocket.getOutputStream());
System.out.printf("Server received... " + action + " ...action\n");
switch (action) {
case "bottle":
for (int i = 3; i >= 0; i--) {
pstream.println("<p>" + i + " bottles of beer on the wall" + "</p>");
}
pstream.println("<p>" + action + "</p>");
break;
case "echo":
pstream.println("<p>" + action + "</p>");
break;
case "quit":
quitFlag = true;
break;
}
pstream.close();
csocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Running the server to echo your response is easy...making the client or clients are more challenging...simple jsp Client..
<BODY>
<H1>Creating Client/Server Applications</H1>
<%
String serverInput = request.getParameter("serverInput");
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
InputStream inSocket = socket.getInputStream();
OutputStream outSocket = socket.getOutputStream();
String str = serverInput+"\n";
byte buffer[] = str.getBytes();
outSocket.write(buffer);
while ((character = inSocket.read()) != -1) {
out.print((char) character);
}
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</BODY>
or better yet...
<body>
<%String name = request.getParameter("inputString");%>
<h1>Creating Client Applications</h1>
<p>Client Sent... <%=name%> ...to Server</p>
<%
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
OutputStream outSocket = socket.getOutputStream();
String str = name;
byte buffer[] = str.getBytes();
outSocket.write(buffer);
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</body>