Socket Client stuck on 'waiting for message from server.' - java

Backstory:
I created a Barcode Scanning app that can connect with my works server. The Barcode app functions perfectly, however, I have no experience with socket connections to servers. So in order to not mess up any code in the Barcode app I copied a tutorial for a socket connection and edited it. Once I can get the test code to complete a connection and send data back and forth, I will implement it into the Barcode app.
The Problem:
When I click my button that says "Connect to server" I get this:
03-23 11:55:52.174 6438-6459/com.example.vipin.client I/Client: Waiting for message from server...
Pasted below is the code. I have removed the IP address and Port for security reasons.
package com.example.vipin.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Client extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = Client.class.getSimpleName();
public static final int SERVERPORT = 0000;
public static final String SERVER_IP = "000.000.0.0";
ClientThread clientThread;
Thread thread;
TextView messageTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageTv = (TextView) findViewById(R.id.messageTv);
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
messageTv.append(message + "\n");
}
});
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
messageTv.setText("");
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.send_data) {
clientThread.sendMessage("Hello from Client");
Log.i(TAG, "Sending message to server...");
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
Log.i(TAG, "Waiting for message from server...");
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
Log.i(TAG, "Message received from the server : " + message);
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
updateMessage(getTime() + " | Server : " + message);
break;
}
updateMessage(getTime() + " | Server : " + message);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
void sendMessage(String message) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
Log for the button click event is here https://pastebin.com/6wbvLj6w

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import javax.imageio.ImageIO;
public class ServerPrintScreen
extends Thread {
private ServerSocket serverSocket;
public ServerPrintScreen(int port)
throws IOException, SQLException, ClassNotFoundException, Exception {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(0);
}
public void run() {
try {
while (true) {
Socket clientSocket = serverSocket.accept();
Throwable localThrowable3 = null;
try {
System.out.println("client connected");
clientSocket.setKeepAlive(true);
String httpResponse = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nAccept-Ranges: bytes\r\nContent-Disposition: inline;filename=screenShot.jpg\r\nContent-Type: image/jpg\r\n\r\n";
BufferedImage originalImage = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
ImageIO.write(originalImage, "jpg", clientSocket.getOutputStream());
clientSocket.getOutputStream().flush();
clientSocket.getOutputStream().close();
clientSocket.close();
System.out.println("sent");
} catch (Throwable localThrowable1) {
localThrowable3 = localThrowable1;
throw localThrowable1;
} finally {
if (clientSocket != null) {
if (localThrowable3 != null) {
try {
clientSocket.close();
} catch (Throwable localThrowable2) {
localThrowable3.addSuppressed(localThrowable2);
}
} else {
clientSocket.close();
}
}
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, Exception {
Thread t = new ServerPrintScreen(25000);
t.start();
}
}

Related

How to establish communication between a computer java application and a android phone?

I have to do a project for the university. I have to connect the mobile phone (android application) with a java desktop project in order to exchange data.
below I propose what I have done for now:
Server1.java
package com.pervasive;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Server1 {
private static Thread Thread1;
static ServerSocket serverSocket;
private static PrintWriter output;
private static BufferedReader input;
public static final int SERVER_PORT = 6789;
public static void main(String[] args) throws IOException {
Thread1 = new Thread(new Thread1());
Thread1.start();
}
static class Thread1 implements Runnable{
InetAddress inetAddress = InetAddress.getLocalHost();
Thread1() throws UnknownHostException {
}
#Override
public void run() {
Socket socket;
try {
serverSocket = new ServerSocket(SERVER_PORT);
System.out.println("Not connected!\nIP: " + inetAddress.getHostAddress() + "\nPort: " + SERVER_PORT + "\n");
try {
socket = serverSocket.accept();
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Connected\n");
new Thread(new Thread2()).start();
} catch (IOException e){
e.printStackTrace();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
private static class Thread2 implements Runnable{
#Override
public void run() {
while(true){
try {
final String message = input.readLine();
if(message != null){
System.out.println("Client: " + message + "\n");
} else {
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Thread3 implements Runnable{
private String message;
Thread3(String message){this.message = message; }
#Override
public void run(){
output.write(message);
output.flush();
System.out.println("Server: " + message + "\n");
}
}
}
While the following code is about the Android application.
MainActivity.java
package com.example.clientapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
#SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity {
Thread Thread1 = null;
EditText etIP, etPort;
TextView tvMessages;
EditText etMessage;
Button btnSend;
String SERVER_IP;
int SERVER_PORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etIP = findViewById(R.id.etIP);
etPort = findViewById(R.id.etPort);
tvMessages = findViewById(R.id.tvMessages);
etMessage = findViewById(R.id.etMessage);
btnSend = findViewById(R.id.btnSend);
Button btnConnect = findViewById(R.id.btnConnect);
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvMessages.setText("");
SERVER_IP = etIP.getText().toString().trim();
SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim());
Thread1 = new Thread(new Thread1());
Thread1.start();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = etMessage.getText().toString().trim();
if (!message.isEmpty()) {
new Thread(new Thread3(message)).start();
}
}
});
}
private PrintWriter output;
private BufferedReader input;
public void OnReceiveMessage(View view) {
output.write((String) tvMessages.getText());
}
class Thread1 implements Runnable {
#Override
public void run() {
Socket socket;
try {
socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT);
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.setText("Connected\n");
}
});
new Thread(new Thread2()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Thread2 implements Runnable {
#Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.append("server: " + message + "\n");
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class Thread3 implements Runnable {
private String message;
Thread3(String message) {
this.message = message;
}
#Override
public void run() {
output.write(message);
output.flush();
runOnUiThread(new Runnable() {
#Override
public void run() {
tvMessages.append("client: " + message + "\n");
etMessage.setText("");
}
});
}
}
}
The problem is the following: I can't connect them.
can you help me?

Server gets stuck waiting for username

I'm trying to create a server/client for the purpose of chatting. I start the server which waits for a client to connect, the client connects, but it gets stuck waiting for the client to send the username.
Here is the server:
package chat_server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Chat_Server {
private ServerSocket ss;
private Socket connection;
private List<ClientT> users;
private static int usersNumber;
public Chat_Server() {
users = new ArrayList<ClientT>();
usersNumber = 1;
try {
ss = new ServerSocket(2016);
} catch (IOException e) {
e.printStackTrace();
System.err.println(3);
}
}
public void acceptRequests() throws IOException {
while (true) {
try {
connection = ss.accept();
ClientT ct = new ClientT(connection);
users.add(ct);
System.out.print("Connected users: ");
for(int i = 0; i < users.size(); i++)
System.out.print(users.get(i) + " ");
System.out.println();
ct.start();
} catch (IOException e) {
System.out.println("Could not accept connection from client: "
+ e);
System.err.println(4);
}
}
}
}
class ClientT extends Thread {
private Socket s;
private BufferedReader in;
private DataOutputStream out;
private String userName = "a";
private String message;
int userNr;
public ClientT(Socket _s) {
this.s = _s;
userNr = usersNumber++;
System.out.println("In client: s = " + s + " userNr = " + userNr);
try {
System.out.println("Creating 'in' and 'out' objects");
out = new DataOutputStream(s.getOutputStream());
in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
System.out.println("Catching username...");
**//--it gets stuck here--**
userName = (String) in.readLine();
System.out.println(userName + " connected...");
} catch (IOException e) {
e.printStackTrace();
System.err.println(1);
}
}
public void run() {
System.out.println("In ClientT run...");
while (true) {
try {
message = in.readLine();
System.out.println("Message: " + message);
System.out.println("Notifying all clients!");
messageNotifyAll(message);
} catch (IOException e) {}
}
}
}
public static void main(String[] args) throws IOException {
Chat_Server cs = new Chat_Server();
System.out.println("Accepting requests...");
cs.acceptRequests();
}
}
And here the the client:
package chatClient;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Client extends JFrame {
private JTextArea textArea;
private JScrollPane scrollPane;
private JPanel panelButtons;
private JPanel panelList;
private JButton send;
private JButton disconnect;
#SuppressWarnings("rawtypes")
private JList userList;
private JLabel connectedUsers;
private JTextField text;
private JButton sendMessage;
private String name;
private Socket s;
BufferedReader in;
DataOutputStream out;
#SuppressWarnings("rawtypes")
public Client(String _name) throws InterruptedException {
System.out.println("Loading GUI...");
//GUI left out
System.out.println("Loading GUI finished...");
connectToServer();
}
public void connectToServer() throws InterruptedException {
try {
textArea.append("Connecting to server...\n");
s = new Socket("localhost", 2016);
textArea.append("Connected to " + s.getInetAddress() + ":" + s.getPort() +" as " + name + "...");
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new DataOutputStream(s.getOutputStream());
new waitForMessage().start();
out.writeBytes(name);
} catch (UnknownHostException e) {
textArea.append("Server not running!");
// e.printStackTrace();
} catch (IOException e) {
textArea.append(e + "\n");
try {
disconnectFromServer();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void disconnectFromServer() throws IOException {
s.close();
System.out.println("Disconnected!");
}
public class FrameExit extends WindowAdapter {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
}
public class Disconnect implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
s.close();
System.out.println("Disconnecting...");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class Send implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
System.out.println("Sending message: " + text.getText());
out.writeBytes(text.getText());
text.setText("");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class waitForMessage extends Thread {
#Override
public void run() {
System.out.println("Waiting for message!");
while (true) {
try {
String message = in.readLine();
System.out
.println("Message received! Displaying message in GUI!");
textArea.append(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//I have a login GUI from where I start the Client
}
}
Any help would be appreciated!
Server side seems to expect a line to read, but there is no line break sent from the client side.
Also, consider adding out.flush() after you write, to ensure that the data is actually sent.
out.writeBytes(name + System.getProperty("line.separator"));
out.flush();
Note that you could use a PrintWriter instead, which has println methods to take care of new lines.
See : What is the Difference between PrintWriter and DataOutputStream?

SocketChannel sockets not reading data

Here is my code. From the TestServer, I'm trying to send data through an outputstream and have it received from the test client. I'm using a SocketChannel because I need the client to listen on 3 ports at the same time. At the moment, i'm only trying to read from one socket. However it doesnt seem to be receiving any data from the server. For the run method of KBThread, if I uncomment the nodata println, that will execute over and over.
TestServer.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class TestServer extends JPanel implements KeyListener, MouseListener, MouseMotionListener {
private final int MAX_CLIENTS = 8;
JPanel listenerPanel = new JPanel();
JFrame listenerFrame = new JFrame();
static DataOutputStream kbOut;
static DataOutputStream mOut;
static Socket dataSocket;
public TestServer() {
this.setFocusable(true);
listenerPanel.addKeyListener(this);
listenerPanel.addMouseMotionListener(this);
listenerFrame.add(listenerPanel);
listenerFrame.setSize(1376,808); // 10 more x, 40 more y.
listenerFrame.setVisible(true);
listenerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
listenerPanel.requestFocusInWindow();
}
public static void main(String[] args) {
new TestServer().startServer();
}
public void startServer() {
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(MAX_CLIENTS);
Runnable serverTask = () -> {
try {
ServerSocket serverSocket = new ServerSocket(1111);
System.out.println("Waiting for clients.");
while (true) {
Socket clientSocket = serverSocket.accept();
clientProcessingPool.submit(new ClientTask(clientSocket));
}
} catch (IOException ex) {
System.err.println("Error with client socket.");
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
private class ClientTask implements Runnable {
private final Socket clientSocket;
private ClientTask(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
try {
String clientIP = clientSocket.getInetAddress().getHostAddress();
System.out.println("Client connected from " + clientIP);
Socket kbSocket = new Socket(clientIP, 1112);
System.out.println("Keyboard socket connected to " + clientIP);
kbOut = new DataOutputStream(kbSocket.getOutputStream());
Socket mSocket = new Socket(clientIP, 1113);
System.out.println("Mouse socket connected to " + clientIP);
mOut = new DataOutputStream(mSocket.getOutputStream());
//new TestServer().startKBServer(clientIP);
//new TestServer().startMServer(clientIP);
try {
clientSocket.close();
} catch (IOException ex) {
}
} catch (IOException ex) {
Logger.getLogger(TestServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void startKBServer(String clientAddress) {
Runnable kbTask = () -> {
try {
Socket kbSocket = new Socket(clientAddress, 1112);
System.out.println("Keyboard socket connected to " + clientAddress);
new KBTask(kbSocket);
} catch (IOException ex) {
System.out.println("Error Calling Back " + clientAddress);
}
};
Thread kbThread = new Thread(kbTask);
kbThread.start();
}
private class KBTask implements Runnable {
private final Socket kbSocket;
private KBTask(Socket kbSocket) {
this.kbSocket = kbSocket;
}
#Override
public void run() {
try {
kbOut = new DataOutputStream(kbSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(TestServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void keyPressed(KeyEvent ke) {
try {
int key = ke.getKeyCode();
System.out.println("Key Pressed: " + key);
kbOut.writeInt(key);
kbOut.flush();
} catch (IOException ex) {
System.out.println("Error writing key data to server");
}
}
#Override
public void keyReleased(KeyEvent ke) {
try {
int key = ke.getKeyCode();
System.out.println("Key Pressed: " + -key);
kbOut.writeInt(-key);
kbOut.flush();
} catch (IOException ex) {
System.out.println("Error writing -key data to server");
}
}
#Override
public void mouseMoved(MouseEvent me) {
try {
int mouseX = me.getX();
int mouseY = me.getY();
if (mOut != null) {
mOut.writeInt(mouseX);
mOut.writeInt(mouseY);
mOut.flush();
System.out.println("Mouse Moved To: " + mouseX + "," + mouseY);
}
} catch (IOException | NullPointerException ex) {
System.out.println("Error writing mouse data to server");
}
}
#Override
public void mouseClicked(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseDragged(MouseEvent me) {
}
#Override
public void keyTyped(KeyEvent ke) {
}
}
TestClient.java
import java.awt.AWTException;
import java.awt.Robot;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestClient {
private final static String SERVER_IP = "192.168.0.50";
JPanel clientPanel = new JPanel();
JFrame clientFrame = new JFrame();
public void setupGUI() {
clientFrame.add(clientPanel);
clientFrame.setSize(200,200);
clientFrame.setVisible(true);
clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clientPanel.requestFocusInWindow();
}
public static void main(String[] args) {
try {
new TestClient().setupGUI();
Robot keyRobot = new Robot();
Socket firstSocket = new Socket(SERVER_IP, 1111);
System.out.println("Connected to Commander. Address sent. Waiting for callback.");
firstSocket.close();
Selector selector = Selector.open();
int ports[] = new int[] { 1112, 1113 };
for (int port : ports) {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(port));
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
while (true) {
// After the 2 accept methods fire, it stops here and program doesnt continue.
selector.select();
Set setKeys = selector.selectedKeys();
Iterator selectedKeys = setKeys.iterator();
while (selectedKeys.hasNext()) {
SelectionKey selectedKey = (SelectionKey) selectedKeys.next();
if (selectedKey.isAcceptable()) {
SocketChannel socketChannel = ((ServerSocketChannel) selectedKey.channel()).accept();
socketChannel.configureBlocking(false);
switch (socketChannel.socket().getLocalPort()) {
case 1112:
System.out.println("Keyboard socket open.");
Runnable kbr = new KBThread(socketChannel.socket());
new Thread(kbr).start();
break;
case 1113:
System.out.println("Mouse socket open.");
break;
}
}
selectedKeys.remove();
}
}
} catch (ConnectException ece) {
System.out.println("Failed to connect to server: " + SERVER_IP);
} catch (IOException | AWTException eio) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, eio);
}
}
private static class KBThread implements Runnable {
private final Socket kbSocket;
private int dataID = 0;
private KBThread(Socket kbSocket) {
this.kbSocket = kbSocket;
}
#Override
public void run() {
try {
DataInputStream kbDis = new DataInputStream(kbSocket.getInputStream());
while (true) {
try {
if (kbDis.available() > 0) {
dataID = kbDis.readInt();
System.out.println(dataID);
}
//else System.out.println("noData");
} catch (IOException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (IOException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
This is not how IO multiplexing is supposed to work.
First, don't remove from selectedKeys - after you accepted two connections there's nothing to select on, so the loop in the main thread blocks, and event if new connections are arriving you are not accepting them anymore. - this was wrong, I was confused about Java iterators, it's been a long time ...
Then, once a connection is accepted and marked non-blocking, add it to the same selector with OP_READ. Check for readable event in the loop, read from the socket. You don't need threads for this.
Alternatively, if you want to go with threads, don't set accepted client connection as non-blocking, just do regular reads from it in the dedicated thread.
Edit 0:
The best advise I can offer is to go over some good Java NIO tutorial. There many on the Intenet, but you can start here:
http://docs.oracle.com/javase/1.5.0/docs/guide/nio/example/index.html
http://tutorials.jenkov.com/java-nio/index.html
Don't have enough rep for comments so posting as answer. I am no expert but I believe you will have to use a PrintWriter on sockets output stream to pass the text back and forth. Here thisClient is a socket.
writer = new PrintWriter(thisClient.getOutputStream());
System.out.println("Transmitting");
writer.println(msg);
writer.flush();

socket not writing to server

There are question with the same problem but they are not helping me out.
Below is the code I've been working on where the ServerSocket not receiving any message from client Socket.
Server
package rescue_server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.TreeMap;
/**
*
* #author Mohammad Faisal
*/
public class RServer {
private TreeMap<String, PrintWriter> clients;
private static final int PORT = 6621;
private class ClientHandler implements Runnable {
private PrintWriter writer;
private BufferedReader reader;
public ClientHandler(Socket client) {
try {
writer = new PrintWriter(client.getOutputStream());
reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
#Override
public void run() {
System.out.println("client handler thread started");
String msg;
try {
while ((msg = reader.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public RServer() {
clients = new TreeMap<>();
}
public void start() {
try {
ServerSocket server = new ServerSocket(RServer.PORT);
while (true) {
System.out.println("waiting....");
Socket client = server.accept();
Thread tclient = new Thread(new ClientHandler(client));
tclient.setDaemon(true);
tclient.start();
System.out.println("got a connection.");
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
new RServer().start();
}
}
Client
package rescue_client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
/**
*
* #author Mohammad Faisal
*/
public class RClient {
private final static int SERVER_PORT = 6621;
private final static String SERVER_IP = "127.0.0.1";
private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private class ServerHandler implements Runnable {
#Override
public void run() {
System.out.println("server handler started.");
String msg;
try {
while ((msg = reader.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public RClient() {
JFrame frame = new JFrame(SERVER_IP);
frame.setVisible(true);
frame.setBounds(10, 20, 100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void startServerHandler() {
Thread tserver = new Thread(new ServerHandler());
tserver.setDaemon(true);
tserver.start();
sendWelcomeMsg();
}
private void sendWelcomeMsg() {
try {
writer.write(InetAddress.getLocalHost().getHostName());
writer.flush();
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
}
writer.flush();
}
public void start() {
System.out.println("starting client...");
try {
socket = new Socket(RClient.SERVER_IP, RClient.SERVER_PORT);
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
startServerHandler();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
new RClient().start();
}
}
The problem is I'm not getting the message on server from client.
From JavaDoc:
A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
So you have to add one of these in your String that is being sent.

Android tcp client connects then disconnect from java server

I am doing java server on my pc and having my android device connect to it. I can connect it but it disconnects as soon as it connects. I am sure there is something I need to do on the android side but I am little lost on it. I have the internet permission so that is fine.
Also ignore the commented code I was sending image from my android to pc. Also ignore the savebitmap and take screenshot I don't think its affecting the connection if its not being called.
Java Server:
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*; //access JFrame
import javax.swing.text.html.HTMLDocument.Iterator;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
public class tcpmain {
BufferedReader in;
static final int PORT = 9000;
public static void main(String[] args) {
// TODO Auto-generated method stub
//lines to make the gui frame
JFrame mainframe = new JFrame();
mainframe.setTitle("TCP Listener");
mainframe.setSize(600,800);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setVisible(true);
ServerSocket serverSocket = null;
Socket socket = null;
try{
serverSocket = new ServerSocket(PORT);
//Receive code
/*int filesize=450660;
int bytesRead;
int current=0;
//receive file
byte [] mybytearray = new byte [filesize];
InputStream is = srsvsock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Andy\\Desktop\\testimage.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;*/
/*do{
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();*/
}
catch(Exception e){
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
JOptionPane.showMessageDialog(null, "Client connected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new threa for a client
new EchoThread(socket).start();
if ( socket != null && !socket.isClosed() ){
try {
socket.close();
JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
client handler for java server
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket){
this.socket = clientSocket;
}
public void run(){
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try{
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
out = new DataOutputStream(socket.getOutputStream());
}catch(Exception e){
return;
}
String line;
while(true){
try{
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")){
socket.close();
return;
}else{
out.writeBytes(line+ "\n\r");
out.flush();
}
}catch(Exception e){
e.printStackTrace();
return;
}
}
}
}
Here is android client:
package com.example.tcpsocket;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 9000;
private static final String SERVER_IP = "192.168.1.113";
Bitmap bitmap;
File imagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnconnect = (Button)findViewById(R.id.button1);
btnconnect.setOnClickListener(connect);
}
private OnClickListener connect = new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Bitmap bitmap = takeScreenshot();
// saveBitmap(bitmap);
new Thread(new clienthread()).start();
}
};
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap){
File imagePath = new File("sdcard/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
new Thread(new clienthread()).start();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class clienthread implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
/*File imagePath = new File("sdcard/screenshot.jpg");
byte[] mybytearray = new byte[450560];
FileInputStream fis = new FileInputStream(imagePath);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.close();*/
}
catch(Exception e){
}
}
}
}
Here:
new EchoThread(socket).start();
if ( socket != null && !socket.isClosed() ){
try {
socket.close();//Don't do this here!!!!!!
JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You shouldn't close your socket after you started your Thread. The closing of the socket should be the job of the EchoThread after you finished communicating with it. You can insert this line at the end of run() method socket.close(); so it closes itself when you're done.
Looks like it is most likely due to this line:
if ( socket != null && !socket.isClosed() ){
If your socket was previously opened and you passed if off to the thread to handle, the socket would still be open and socket.isClosed() will return false and you'll immediately close the socket and clean it up in your main thread.

Categories