Websocket server.run() don't allow followed codes to start - java

I have the following web-socket server code from (https://github.com/TooTallNate/Java-WebSocket):
public class WebsocketServer extends WebSocketServer {
private static int PORT = 2005;
private Set<WebSocket> conns;
public WebsocketServer() {
super(new InetSocketAddress(PORT));
conns = new HashSet<>();
}
#Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conns.add(conn);
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
#Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
conns.remove(conn);
System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
#Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received: " + message);
for (WebSocket sock : conns) {
sock.send(messageToSend);
}
}
#Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
if (conn != null) {
conns.remove(conn);
// do some thing if required
}
System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
public static void main(String[] args) throws IOException, InterruptedException {
WebsocketServer server = new WebsocketServer();
server.run();
BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String in = sysin.readLine();
server.sendToAll(in);
if (in.equals("exit")) {
server.stop();
break;
} else if (in.equals("restart")) {
server.stop();
server.start();
break;
}
}
}
public void sendToAll(String text) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(text);
}
}
}
}
The codes works fine, but all codes that comes after server.run(); won't start/work! that part I need to send messages from Java console to client.
What I am doing wrong?
Note: My client works in JavaScript and can connect to the server

You need to start() Runnable class, not run() it directly
server.start();
instead of
server.run();

Related

TCP Java Android Server / C# Windows Client Communication not working

I am currently trying to set up an App for an Android Device, which can communicate with Devices in the same Network via TCP connection. Said Devices run on Windows and therefore I created a simple C# TCP Client program to connect to the TCP Server. The connection gets established when the Server App is already running and a Client tries to connect to it. Both sides (Server/Client) confirm that the connection got established. When I send data from the server via DataOutputStream back to the client, the client confirms, that he got the message. But when I try to send data from the client and try to read it on the server via InputStreamReader the server never reacts to incoming messages.
Below lies the Java Android server code:
public class TCPServer {
public enum ServerCommands { TURN_OFF }
private static ServerSocket serverSocket;
private static final Handler HANDLER = new Handler(Looper.getMainLooper());
private static final int SERVERPORT = 5040;
private static final HashMap<InetAddress, ServerClientCommunicationThread> connectedClientThreads = new HashMap<>();
private interface OnUpdateUIListener {
void onShowStatus(String status);
}
private static OnUpdateUIListener listener;
public static void InitServer(Consumer<String> showStatus) {
listener = new OnUpdateUIListener() {
#Override
public void onShowStatus(String status) {
// Use the handler so we're not trying to update the UI from the bg thread
HANDLER.post(new Runnable(){
#Override
public void run(){
showStatus.accept(status);
}
});
}
};
Thread serverThread = new Thread(new ServerThread());
serverThread.start();
}
public static void OnStop(){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void SendMessageToClient(InetAddress clientIP, ServerCommands action){
ServerClientCommunicationThread clientThread = connectedClientThreads.get(clientIP);
listener.onShowStatus("Trying to send Data to client!");
if (clientThread != null)
clientThread.getHandler().sendEmptyMessage(action.ordinal());
}
private static class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
boolean error = false;
while (!Thread.currentThread().isInterrupted() && !error) {
try {
listener.onShowStatus("Start listening for clients!");
socket = serverSocket.accept();
listener.onShowStatus("Found client: " + socket.getInetAddress());
ClientServerCommunicationThread clientCommThread = new ClientServerCommunicationThread(socket);
new Thread(clientCommThread).start();
ServerClientCommunicationThread serverCommThread = new ServerClientCommunicationThread("CommThread", socket);
new Thread(serverCommThread).start();
connectedClientThreads.put(serverCommThread.clientSocket.getInetAddress(), serverCommThread);
} catch (Exception e) {
listener.onShowStatus("Could not establish client connection: " + e);
error = true;
}
}
}
}
private static class ServerClientCommunicationThread extends HandlerThread {
private DataOutputStream outputStream;
private Socket clientSocket;
private Handler commHandler;
public ServerClientCommunicationThread(String name, Socket clientSocket) {
super(name);
try {
this.clientSocket = clientSocket;
this.outputStream = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
listener.onShowStatus("ERROR: could not open ReaderStream: " + e);
}
}
#SuppressLint("HandlerLeak")
#Override
protected void onLooperPrepared(){
commHandler = new Handler(){
#Override
public void handleMessage(Message msg){
try {
outputStream.write(msg.what);
listener.onShowStatus("Sent action: " + msg.what);
outputStream.flush();
}
catch(Exception e){
listener.onShowStatus("Could not send data to client: " + clientSocket.getInetAddress() + " " + e);
}
}
};
listener.onShowStatus("Start Server Communication Thread");
}
public Handler getHandler(){
return commHandler;
}
}
private static class ClientServerCommunicationThread extends Thread {
private BufferedReader input;
private final Socket clientSocket;
public ClientServerCommunicationThread(Socket clientSocket){
super();
this.clientSocket = clientSocket;
try{
this.input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
listener.onShowStatus("ERROR: could not open ReaderStream: " + e);
}
}
#Override
public void run(){
listener.onShowStatus("Start Client Communication Thread");
boolean connectionStable = true;
while (!Thread.currentThread().isInterrupted() && connectionStable) {
try {
String read = input.readLine();
//It never reaches this debug message!
listener.onShowStatus("Received message: " + read);
} catch (IOException e) {
e.printStackTrace();
listener.onShowStatus("ERROR: could not read message: " + e);
connectionStable = false;
}
}
try {
input.close();
clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Below lies my C# client code.
I am using the SuperSimpleTCP library for my C# code.
namespace SimpleTCPProgram
{
internal class TCPClient
{
private static SimpleTcpClient tcpClient;
private static int udpPort = 5041;
private static int tcpPort = 5040;
private static string macAddr;
enum ServerCommands { TURN_OFF = 0 }
// Main Method
static public void Main(String[] args)
{
InitTCPClient("192.168.1.4");
Console.ReadKey();
tcpClient.Send("Hello there");
Console.WriteLine("Sent data: " + tcpClient.Statistics.SentBytes.ToString());
Console.ReadKey();
}
private static void InitTCPClient(string serverIP)
{
try
{
tcpClient = new SimpleTcpClient(serverIP + ":" + tcpPort);
tcpClient.Events.Connected += Events_Connected;
tcpClient.Events.Disconnected += Events_Disconnected;
tcpClient.Events.DataReceived += Events_DataReceived;
tcpClient.Connect();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private static void Events_Connected(object sender, ConnectionEventArgs e)
{
Console.WriteLine("Connected to Server: " + e.IpPort);
}
private static void Events_Disconnected(object sender, ConnectionEventArgs e)
{
}
private static void Events_DataReceived(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
{
string dataString = Encoding.UTF8.GetString(e.Data);
Console.WriteLine("Received Data: " + dataString);
ServerCommands serverCommand = (ServerCommands)int.Parse(dataString);
switch (serverCommand)
{
case ServerCommands.TURN_OFF:
var psi = new ProcessStartInfo("shutdown", "/s /t 0");
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
break;
default:
break;
}
}
}
}
Wireshark seems to confirm that the message has been sent to the server.
It even catches a message sent back by the server to the client in response.
I am testing this on a test-router which doesn't have internet access and no firewall active.
My server app has the following permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:ignore="ManifestOrder"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
TLDR: My Android java server doesn't get any C# client messages sent via TCP connection.

Why isn't my client socket inputstream receiving message sent from server socket outputstream

This is the SocketServer code that generates a server thread
public class ProcessorCorresponder {
protected final static Logger logger = LogManager.getLogger( ProcessorCorresponder.class );
private static int port = Integer.parseInt(PropertiesLoader.getProperty("appserver.port") == null ? "666" : PropertiesLoader.getProperty("appserver.port"));
private static int maxConnections = Integer.parseInt(PropertiesLoader.getProperty("appserver.maxconnections") == null ? "666" : PropertiesLoader.getProperty("appserver.maxconnections"));
public static void main(String[] args) {
logger.info("Starting server .. "
+ "[port->" + port
+ ",databaseName->" + databaseName + "]");
try (ServerSocket listener = new ServerSocket();) {
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(port));
Socket server;
int i = 0;
while((i++ < maxConnections) || (maxConnections == 0)) {
server = listener.accept();
logger.debug(
"New Thread listening on " + server.getLocalAddress().toString() + ":" + server.getLocalPort()
+ ", initiated from IP => " + server.getInetAddress().toString() + ":" + server.getPort()
);
MySocketServer socSrv = new MySocketServer (server);
Thread t = new Thread( socSrv );
t.start();
}
} catch (Exception ex) {
logger.error("Error in ProcessorInterface", ex);
}
}
}
Server code: This is a thread to handle one connection, there is a program that monitors a serversocket and spins off request threads as needed.
public class MySocketServer implements Runnable {
protected final static Logger logger = LogManager.getLogger(MySocketServer.class);
private final Socket server;
// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;
private StringBuffer buffHeartbeatMessage = new StringBuffer().append((char) 0).append((char) 0).append((char) 0)
.append((char) 0).append((char) 0).append((char) 0);
private Heartbeat heartbeat = new Heartbeat(/* 60 */3000, buffHeartbeatMessage.toString());
public MySocketServer(Socket server) {
this.server = server;
}
#Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
BufferedOutputStream out = new HeartbeatBufferedOutputStream(this.server.getOutputStream(),
heartbeat)) {
final StreamListener listener = new StreamListener(in);
listener.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getID() == ActionEvent.ACTION_PERFORMED) {
if (event.getActionCommand().equals(StreamListener.ERROR)) {
logger.error("Problem listening to stream.");
listener.setShouldContinue(false);
stopRunning();
} else {
String messageIn = event.getActionCommand();
if (messageIn == null) { // End of Stream;
stopRunning();
} else { // hey, we can do what we were meant for
logger.debug("Request received from client");
// doing stuff here
...
// done doing stuff
logger.debug("Sending Client Response");
try {
sendResponse(opResponse, out);
} catch (Exception ex) {
logger.error("Error sending response to OP.", ex);
}
}
}
}
}
});
listener.start();
while (shouldContinue) {
// loop here until shouldContinue = false;
// this should be set to false in the ActionListener above
}
heartbeat.setShouldStop(true);
return;
} catch (Exception ex) {
logger.error("Error in ESPSocketServer", ex);
return;
}
}
private void stopRunning() {
shouldContinue = false;
}
private void sendResponse(ClientResponse opResponse, BufferedOutputStream out) throws Exception {
logger.debug("Before write");
out.write(opResponse.getResponse().getBytes());
logger.debug("After write. Before flush");
out.flush();
logger.debug("After flush");
// this log message is in my logs, so I know the message was sent
}
}
My StreamListener class.
public class StreamListener extends Thread {
protected final static Logger logger = LogManager.getLogger(StreamListener.class);
public final static String ERROR = "ERROR";
private BufferedReader reader = null;
private List<ActionListener> actionListeners = new ArrayList<>();
private boolean shouldContinue = true;
public StreamListener(BufferedReader reader) {
this.reader = reader;
}
#Override
public void run() {
while (shouldContinue) {
String message;
try {
// client blocks here and never receives message
message = reader.readLine();
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, message);
fireActionPerformed(event);
} catch (IOException e) {
e.printStackTrace();
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ERROR);
fireActionPerformed(event);
}
}
}
public void setShouldContinue(boolean shouldContinue) {
this.shouldContinue = shouldContinue;
}
public boolean getShouldContinue() {
return shouldContinue;
}
public boolean addActionListener(ActionListener listener) {
return actionListeners.add(listener);
}
public boolean removeActionListener(ActionListener listener) {
return actionListeners.remove(listener);
}
private void fireActionPerformed(ActionEvent event) {
for (ActionListener listener : actionListeners) {
listener.actionPerformed(event);
}
}
}
My Heartbeat class
public class Heartbeat extends Thread {
private BufferedOutputStream bos = null;
private int beatDelayMS = 0;
private String message = null;
private boolean shouldStop = false;
public Heartbeat(int beatDelayMS, String message) {
this.beatDelayMS = beatDelayMS;
this.message = message;
setDaemon(true);
}
#Override
public void run() {
if (bos == null) { return; }
while(!shouldStop) {
try {
sleep(beatDelayMS);
try {
bos.write(message.getBytes());
bos.flush();
} catch (IOException ex) {
// fall thru
}
} catch (InterruptedException ex) {
if (shouldStop) {
return;
}
}
}
}
public void setBufferedOutputStream(BufferedOutputStream bos) {
this.bos = bos;
}
public BufferedOutputStream getBufferedOutputStream() {
return bos;
}
public void setShouldStop(boolean shouldStop) {
this.shouldStop = shouldStop;
}
public boolean getShouldStop() {
return shouldStop;
}
}
My HeartbeatBufferedOutputStream
public class HeartbeatBufferedOutputStream extends BufferedOutputStream {
private Heartbeat heartbeat = null;
public HeartbeatBufferedOutputStream(OutputStream out, Heartbeat heartbeat) {
super(out);
this.heartbeat = heartbeat;
this.heartbeat.setBufferedOutputStream(this);
heartbeat.start();
}
#Override
public synchronized void flush() throws IOException {
super.flush();
heartbeat.interrupt();
}
}
And finally here is the "Client" class
public class Mockup extends Thread {
protected final static Logger logger = LogManager.getLogger(Mockup.class);
// because we are using threads, we must make this volatile, or the class will
// never exit.
private volatile boolean shouldContinue = true;
public static void main(String[] args) {
new Mockup().start();
}
#Override
public void run() {
try (Socket socket = new Socket("localhost", 16100);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
final StreamListener listener = new StreamListener(in);
listener.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getID() == ActionEvent.ACTION_PERFORMED) {
if (event.getActionCommand().equals(StreamListener.ERROR)) {
logger.error("Problem listening to stream.");
listener.setShouldContinue(false);
stopRunning();
} else {
String messageIn = event.getActionCommand();
if (messageIn == null) { // End of Stream;
stopRunning();
} else { // hey, we can do what we were meant for
// convert the messageIn to an OrderPower request, this parses the information
logger.info("Received message from server. [" + messageIn + "].");
}
}
}
}
});
listener.start();
StringBuffer buff = new StringBuffer("Some message to send to server");
logger.info("Sending message to server [" + buff.toString() + "]");
out.write(buff.toString().getBytes());
out.flush();
boolean started = false;
while (shouldContinue) {
if (!started) {
logger.debug("In loop");
started = true;
}
// loop here until shouldContinue = false;
// this should be set to false in the ActionListener above
}
logger.info("Exiting Mockup");
return;
} catch (Exception ex) {
logger.error("Error running MockupRunner", ex);
}
}
private void stopRunning() {
shouldContinue = false;
}
}
I have confirmed from logging messages that the Server sends a message to the BufferedOutputStream, and is flushed, but the Client logs indicate that it is blocked on the reader.readLine() and never gets the message.
You are reading lines but you are never writing lines. Add a line terminator to what you send.

How to receive message without using createChat for android XMPP chat smack api

Hi I am confused with the logic of implementing chatManagerListener interface inside a Service.
Below is my service code:
public class MyService3 extends Service {
ChatManager chatManager;
ChatManagerListener chatManagerListener;
AbstractXMPPConnection abstractXMPPConnection;
MyXmpp2 myXmpp2;
public MyService3() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Myservice3:","Started");
abstractXMPPConnection = myXmpp2.getConnection();
abstractXMPPConnection.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
Log.d("XMPPConnection:","connected");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d("XMPPConnection:","authenticated");
//Once authenticated start listening for messages
}
#Override
public void connectionClosed() {
Log.d("XMPPConnection:","connectionClosed");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.d("XMPPConnection:","connectionClosedOnError");
}
#Override
public void reconnectionSuccessful() {
Log.d("XMPPConnection:","reconnectionSuccessful");
}
#Override
public void reconnectingIn(int seconds) {
Log.d("XMPPConnection:","reconnectingIn");
}
#Override
public void reconnectionFailed(Exception e) {
Log.d("XMPPConnection:","reconnectionFailed");
}
});
Log.d("isOnline:", myXmpp2.getConnection().isConnected() + "");
chatManager = ChatManager.getInstanceFor(abstractXMPPConnection);
chatManager.addChatListener(chatManagerListener);
chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Log.d("Hello::","World");
//NOT WORKNIG
if(message.getBody()!=null)
{
Log.d("Message::",message.getBody());
}
}
});
}
};
return super.onStartCommand(intent, flags, startId);
}
}
Whenever is send a packet i am getting this following exception .I don't kno why its arising
Exception in packet listener java.lang.NullPointerException: Attempt to invoke interface method 'void org.jivesoftware.smack.chat.ChatManagerListener.chatCreated(org.jivesoftware.smack.chat.Chat, boolean)' on a null object reference
at org.jivesoftware.smack.chat.ChatManager.createChat(ChatManager.java:255)
at org.jivesoftware.smack.chat.ChatManager.createChat(ChatManager.java:287)
In simple terms i want to know how to implement ChatMessage listener in the service.Please be kind
You need to createchat once you successfully connected & authenticated
Once you got the instance of ChatManager.For package transmission you need to createchat with peer/group check this link for method to createchat.
chatManager = ChatManager.getInstanceFor(abstractXMPPConnection);
newChat = chatmanager.createChat(userid, chatManagerListener);
once you get the Chat instance you can send package & retrive on your chatmanagerListner
from newChat you can sendMessage
To get Package (message, chat)
You can try below code if your connection/authentication process is done successfully than
final Chat newChat = ChatManager.getInstanceFor(xmppConn).createChat(userJid, new MessageListener() {
#Override
public void processMessage(final Chat arg0, final Message arg1) {
LOG.info("Sent message: " + arg1.getBody());
}
});
try {
final Message message = new Message();
message.setFrom(chatProperties.getDomain());
message.setTo(userJid);
message.setType(Type.normal);
message.setBody(text);
message.setSubject("");
newChat.sendMessage(message);
xmppConn.disconnect();
} catch (final Exception e) {
LOG.error("Error while sending message to " + userName + ": ", e);
}
UPDATE
You can try using PacketListener.
XMPPConnection's addPacketListener method check this link for details.
Add PacketListener to XMPPConnection with PacketFilter type Message
But before adding packetlistner remove if already added any instance in xmppconnection.
Check below code
private PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
if (packet instanceof Message) {
Message message = (Message) packet;
String chatMessage = message.getBody();
}
}
};
private void regiSterPackateListner() {
PacketTypeFilter filter = new PacketTypeFilter(Message.class);
try {
if (packetListener != null) {
//Avoid adding multiple packetlistner
abstractXMPPConnection.removePacketListener(packetListener);
}
abstractXMPPConnection.addPacketListener(packetListener, filter);
} catch (Exception e) {
e.printStackTrace();
}
}
Refer to this example:
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
public class GoogleTalkDemo extends Thread{
private XMPPConnection xmppConnection;
public void connect(String server, int port, String s) throws Exception {
xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port,s));
xmppConnection.connect();
}
public void disconnect(){
if(xmppConnection != null){
xmppConnection.disconnect();
interrupt();
}
}
public void login(String username, String password) throws Exception{
connect("talk.google.com", 5222, "gmail.com");
xmppConnection.login(username, password);
}
public void run(){
try {
login("youtID#sample.com", "your password");
System.out.println("Login successful");
listeningForMessages();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
GoogleTalkDemo gtd = new GoogleTalkDemo();
gtd.run();
}
public void listeningForMessages() {
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class));
PacketCollector collector = xmppConnection.createPacketCollector(filter);
while (true) {
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message message = (Message) packet;
if (message != null && message.getBody() != null)
System.out.println("Received message from "
+ packet.getFrom() + " : "
+ (message != null ? message.getBody() : "NULL"));
}
}
}
}
Hope it will help you.
A simple demo about sending and receiving masseges:
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
public class Test {
public static void main(String args[]) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("127.0.0.1", 5222);
XMPPConnection connection = new XMPPConnection(config);
connection.connect();
connection.login("userx", "123456");
ChatManager cm = connection.getChatManager();
Chat chat = cm.createChat("tongqian#tsw-PC", null);
/*
* add listener
*/
cm.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean create) {
chat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message msg) {
System.out.println(chat.getParticipant() + ":" + msg.getBody());
}
});
}
});
chat.sendMessage("hello");
while(true);
//connection.disconnect();
}
}

Kryonet packet not sent

So I'm trying out kryonet, sending a custom packet, but the listener in my server can't seem to pick it up.
server.addListener(new Listener() {
#SuppressWarnings("unused")
public void received(Connection connection, Object object) {
System.out.println("received");
if (object instanceof Packet) {
Packet p = (Packet) object;
System.out.println(p.name);
}
}
});
Sending:
Packet p = new Packet();
p.name = "test";
client.sendTCP(p);
Reading through other threads, I've tried using new Thread(client).start(); instead of client.start();, and I've added empty constructors to my packet classes, but the client either connects, then hangs and never disconnects (if I'm using new Thread(client).start()) or connects then immediately disconnects (if I'm using client.start()). Nothing is ever printed. Any help is appreciated.
These are the necessary steps to make KryoNet work:
Server server = new Server();
Kryo kryo = server.getKryo();
kryo.register(float[].class);
server.start();
server.bind(2300, 2301);
server.addListener(new Listener() {
public void received(Connection connection, Object object)
{
if(object instanceof float[])
{
float[] array = (float[])object;
}
}
});
Client client = new Client();
Kryo kryo = client.getKryo();
kryo.register(float[].class);
client.addListener(new Listener() {
public void connected(Connection connection)
{
connection.sendTCP(new float[] {5.0f, 6.0f, 7.0f, 8.0f});
}
});
client.start();
client.connect(5000, "127.0.0.1”, 2300, 2301);
Of course, you can use client.sendTCP() once you've connected to the server.
Replace the float[] with Packet, and it should work.
You don't need to mess with making threads yourself, KryoNet is already asynchronous, except for the discoverHost() method call if you use it.
EDIT: I whipped up an example project that works.
Packet.java:
public class Packet
{
private String message;
public Packet()
{
}
public Packet(String message)
{
this.message = message;
}
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
}
KryoClient.java:
public class KryoClient
{
private Client client;
public KryoClient() throws IOException
{
client = new Client();
Kryo kryo = client.getKryo();
kryo.register(float[].class);
kryo.register(Packet.class);
//kryo.register(String.class);
client.addListener(new Listener() {
public void connected(Connection connection)
{
//connection.sendTCP(new float[] {5.0f, 6.0f, 7.0f, 8.0f});
connection.sendTCP(new Packet("Hello, Server! You're sexy, rawr :3"));
}
#Override
public void received(Connection connection, Object object)
{
if (object instanceof float[])
{
float[] array = (float[]) object;
for(float a : array)
{
System.out.println(a);
}
}
else if(object instanceof Packet)
{
Packet packet = (Packet) object;
System.out.println("Message: " + packet.getMessage());
connection.sendTCP(new Packet("The packet has arrived to client."));
}
}
#Override
public void disconnected(Connection arg0)
{
System.out.println("Server disconnected.");
}
});
client.start();
client.connect(5000, "127.0.0.1", 2305, 2306);
}
public Client getClient()
{
return client;
}
public void setClient(Client client)
{
this.client = client;
}
}
KryoServer.java:
public class KryoServer
{
private Server server;
public KryoServer() throws IOException
{
server = new Server();
Kryo kryo = server.getKryo();
kryo.register(float[].class);
kryo.register(Packet.class);
//kryo.register(String.class);
server.start();
server.bind(2305, 2306);
server.addListener(new Listener()
{
#Override
public void connected(Connection connection)
{
connection.sendTCP(new Packet("Server says, connected to server."));
}
#Override
public void received(Connection connection, Object object)
{
if (object instanceof float[])
{
float[] array = (float[]) object;
for(float a : array)
{
System.out.println(a);
}
}
else if(object instanceof Packet)
{
Packet packet = (Packet) object;
System.out.println("Message: " + packet.getMessage());
//connection.sendTCP(new Packet("The packet has arrived to server."));
}
}
#Override
public void disconnected(Connection connection)
{
System.out.println("Client disconnected.");
}
});
}
public Server getServer()
{
return server;
}
public void setServer(Server server)
{
this.server = server;
}
}
ClientThread.java:
public class ClientThread extends Thread
{
private KryoClient client;
private volatile boolean running;
public ClientThread(KryoClient client)
{
this.client = client;
running = true;
}
#Override
public void run()
{
long initTime = System.currentTimeMillis();
while(running)
{
if(System.currentTimeMillis() - initTime > 1000)
{
initTime = System.currentTimeMillis();
client.getClient().sendTCP(new Packet("Hello from " + System.currentTimeMillis()));
//should have used Thread.sleep(1000); instead
}
}
}
public void stopThread()
{
running = false;
}
}
MyMain.java:
public class MyMain
{
private static KryoClient kryoClient = null;
private static KryoServer kryoServer = null;
private static ClientThread thread = null;
public static void main(String[] args) throws IOException
{
BufferedReader br = null;
System.out.println("What's up, doc?");
System.out.println("Press '1' for server.");
System.out.println("Press '2' for client.");
try
{
br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int number = Integer.parseInt(line);
if (number == 1)
{
kryoServer = new KryoServer();
System.out.println("Server started.");
}
else if (number == 2)
{
kryoClient = new KryoClient();
System.out.println("Client started.");
thread = new ClientThread(kryoClient);
thread.start();
}
System.out.println("Press a button to exit.");
br.readLine();
System.out.println("Test end.");
}
finally
{
if(kryoClient != null)
{
kryoClient.getClient().stop();
}
if(kryoServer != null)
{
kryoServer.getServer().stop();
}
if (br != null)
{
br.close();
}
if (thread != null)
{
thread.stopThread();
}
}
}
}
And it works.

Socket Client/Server stop method in java

This is the simple client/server socket app for my faculty project. First, the Server class should be run, and then if Client class runs - it prints out the IP address of the local machine and the port that's been used.
I can't figure out one thing:
How and WHERE to create a method in class that will close(stop) the Server? And
how to make this like an event or something, for example if client
sends "stop" it should somehow stop the server...
SERVER.JAVA
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
System.out.println("The server has been summoned.\n");
System.out.println("The server is waiting for client to come...");
try {
ServerSocket servertest = new ServerSocket(2014);
while (true) {
try {
Socket ser = servertest.accept();
new ThreadSer(ser).start();
} catch (IOException e) {}
}
} catch (IOException e) {System.err.println(e);}
}
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
} catch (IOException e) { System.err.println(e); }
}}}
CLIENT.JAVA
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2014);
new OutputThread(socket.getInputStream()).start();
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
#Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}}}
You should constantly ask for the inputstream of the client.. put it in the loop that always accept for the client input..
example:
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
ObjectInputStream input = new ObjectInputStream(s.getInputStream());
while(true)
{
Object object = input.readObject();
if(object instanceof String)
{
String command = ((String) object).trim();
if(command.equals("stop"))
break;
}
}
s.close();
} catch (IOException e) { System.err.println(e); }
}}}

Categories

Resources