I'm trying to write a JavaScript server running on NodeJS using Socket.io that communicates with the client which is written in JAVA.
I have no problem with the server side because I try it with a JavaScript client, so I assumed that the problem came from my java client.
I have this error on my client side :
io.socket.SocketIOException: Error while handshaking
at io.socket.IOConnection.handshake(IOConnection.java:322)
at io.socket.IOConnection.access$600(IOConnection.java:39)
at io.socket.IOConnection$ConnectThread.run(IOConnection.java:199)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8000/socket.io/1/at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at io.socket.IOConnection.handshake(IOConnection.java:313)
This is my code(client side) :
public class BasicExample implements IOCallback {
private SocketIO socket;
public static void main(String[] args) {
try {
new BasicExample();
} catch (Exception e) {
e.printStackTrace();
}
}
public BasicExample() throws Exception {
socket = new SocketIO();
socket.connect("http://localhost:8000", this);
// Sends a string to the server.
socket.send("Hello Server");
// Emits an event to the server.
socket.emit("event", "ILYES");
}
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
#Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
#Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
#Override
public void onConnect() {
System.out.println("Connection established");
}
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
}
Related
I'm making my first steps with netty and I'm wondering about the following behaviour of netty:
When i use the following Handler:
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf inBuffer = (ByteBuf) msg;
String received = inBuffer.toString(CharsetUtil.UTF_8);
System.out.println(dateFormat.format(new Date()) + " Server received: " + received);
ctx.writeAndFlush(Unpooled.copiedBuffer("Hello " + received, CharsetUtil.UTF_8));
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
And I then send a TCP packet with "Packet Sender" I get three packets
the first is from the "packet sender" to the server,
the second is the response from the server (so something like "Hello testtest")
and then .. and I don't know where this packet comes from:
a third one from the server to the "packet sender", without any content
My Server java is:
public class MainNettyApplicationServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(group);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.localAddress(new InetSocketAddress("10.0.0.2", 11111));
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new SimpleServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind().sync();
System.out.println("Server started.");
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully().sync();
}
}
}
I am currently in the process of writing an app which has the phone connect to a server.
Both client and server are using the Kryonet framework.
The problem ist the following :
When the server is running and I then start up the client, the client immediately disconnects from the server but the Programm itself keeps running so it is only possible that the client Thread died for whatever reason.
I am using kryonet-2.21 on both server and client.
I tried my code on Android aswell as on pc.
I also tried to troubleshoot everything I could and tried everything I found searching for my problem.
The Client code :
public class LogicHandler extends Thread {
private Client client;
public LogicHandler() {
}
public Client getClient() {
return client;
}
public void run() {
client = new Client(33554432, 33554432);
new Thread(client).start();
try {
getClient().connect(5000, "localhost", 54555, 54777);
} catch (IOException e) {
e.printStackTrace();
}
Packets.register(getClient());
getClient().addListener(new Listener() {
public void received(Connection connection, Object object) {
System.out.println("received " + object);
if (object instanceof ConnectionResponse) {
}
if (object instanceof ScheduleResponse) {
}
}
public void disconnected(Connection connection) {
}
});
getClient().sendTCP(new ConnectionRequest());
}
public static void main(String[] args) {
new LogicHandler().start();
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("wait");
}
}
}
The Server code :
public class ServerLogicHandler {
private Server server;
private List<Client> clients;
private List<Connection> connections;
public ServerLogicHandler() {
System.out.println("Server is starting!");
server = new Server(33554432, 33554432);
server.start();
try {
server.bind(54555, 54777);
} catch (Exception e) {
server.stop();
System.out.println("Port belegt. Server wird gestoppt!");
System.exit(0);
}
Packets.register(server);
clients = new ArrayList<Client>();
connections = new ArrayList<Connection>();
server.addListener(new Listener() {
public void received(Connection connection, Object object) {
System.out.println("got packet");
if (object instanceof ConnectionRequest) {
System.out.println("size " + connection.sendTCP(new ScheduleResponse()));
}
}
public void disconnected(Connection connection) {
System.out.println("Disco " + connection.getID());
}
public void connected(Connection connection) {
System.out.println(connection.getRemoteAddressTCP().getPort() + " "
+ connection.getRemoteAddressTCP().getAddress());
}
});
System.out.println("Server started!");
}
public Server getServer() {
return server;
}
public static void main(String... args) {
new ServerLogicHandler();
}
}
The client doesn't output anything apart from the 'wait' every second. This means that either the server didn't send any packet or the client closed already. My guess is that the latter happened because the server outputs the following :
Server is starting!
Server started!
54408 /127.0.0.1
Disco 1
When I start a new client the last 2 lines would just repeat e.g. '54890 /127.0.0.1
Disco 2
'
From this I guess that the client closes for whatever reason before even sending any packets. None of my Google searches brang up any success.
I am creating a client and server setup in order to send then server a command and then receive a reply. However when I run it the client throws and EOFException. I understand this is an end of file exception but I am not sure what I am doing wrong, or how I can fix it.
Code for Server:
public class Server {
private ServerSocket server;
private Socket connection;
private ObjectOutputStream output;
private ObjectInputStream input;
//SET UP AND RUN SERVER
public void startRunning() {
try {
server = new ServerSocket(6789, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileRunning();
} catch (Exception e) {
} finally {
closeAll();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//DURING RUN
private void whileRunning() throws IOException {
String message = "You are now connected";
sendMessage(message);
System.out.println("Connected to client");
}
//WAIT FOR CONNECTION THEN DISPLAYS INFO
private void waitForConnection() throws IOException {
System.out.println("Waiting for connection.....");
connection = server.accept();
System.out.println("Now connected to " + connection.getInetAddress().getHostAddress());
}
//SETS UP STREAMS
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
}
//SEND MESSAGE TO CLIENT
private void sendMessage(String message) {
try {
output.writeObject("SERVER - " + message);
output.flush();
System.out.println("SERVER - " + message);
}
catch (Exception e) {
System.out.println("ERROR: Can't send message");
}
}
//CLOSE STREAMS AND SOCKETS
private void closeAll() {
System.out.println("Closing Connections");
try {
output.close();
input.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Code for starting the server:
public class RunServer {
public static void main(String[] args) {
Server server = new Server();
server.startRunning();
}
}
Code for client:
public class Client {
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
public Client(String host) {
serverIP = host;
}
public void startRunning() {
try {
connectToServer();
setupStreams();
whileRunning();
}
catch (Exception e) {
} finally {
closeAll();
}
}
// CONNECT TO SERVER
public void connectToServer() throws IOException {
System.out.println("Attempted connection...");
connection = new Socket(InetAddress.getByName(serverIP), 6789);
System.out.println("Connected to: " + connection.getInetAddress().getHostName());
}
// SET UP STREAMS
private void setupStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
System.out.println("\nStreams Connected");
}
// WHILE CHATTING
private void whileRunning() throws IOException {
do {
try {
message = (String) input.readObject();
System.out.println(message);
} catch (Exception e) {
e.printStackTrace(); //In to view exception
System.out.println("Unable to get message");
System.exit(0); //In to stop it looping forever (Known issue)
}
} while (!message.equals("SERVER - END"));
}
// CLOSE STREAMS AND SOCKETS
public void closeAll() {
System.out.println("Closing sockets, closing streams");
try {
output.close();
input.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Code for starting the client:
public class RunClient {
public static void main(String[] args) {
Client client = new Client("localhost");
client.startRunning();
}
}
When I run the client it constantly loops saying "Unable to get message" forever.
However when I view the exception and exit the code (as added in) I get this problem:
Attempted connection...
Connected to: localhost
Streams Connected
SERVER - You are now connected
java.io.EOFException
Unable to get message
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at main.Client.whileRunning(Client.java:53)
at main.Client.startRunning(Client.java:26)
at main.RunClient.main(RunClient.java:7)
Any help or suggestions would be much appreciated. Thanks :)
EOFException is thrown when you get to the end of the stream, which happens when the peer closes the connection.
You need to catch it separately and not treat it as an error.
I also suggest you change System.exit(0); to break;.
I want use library
And I wan realize this functionality:
connect to my java server
Socket socket = IO.socket("http://127.0.0.1:4444");
socket.io().open(new Manager.OpenCallback() {
#Override
public void call(Exception err) {
if (err != null) {
Log.d("mylog", err.getMessage());
return;
}
Log.d("mylog", "connected");
}
});
Send messge - I do not understand how.
It is my server:
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Server side");
BufferedReader in = null;
PrintWriter out= null;
ServerSocket servers = null;
Socket fromclient = null;
// create server socket
try {
servers = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Couldn't listen to port 4444");
System.exit(-1);
}
try {
System.out.print("Waiting for a client...");
fromclient= servers.accept();
System.out.println("Client connected");
} catch (IOException e) {
System.out.println("Can't accept");
System.exit(-1);
}
in = new BufferedReader(new
InputStreamReader(fromclient.getInputStream()));
out = new PrintWriter(fromclient.getOutputStream(),true);
String input,output;
System.out.println("Wait for messages");
while ((input = in.readLine()) != null) {
if (input.equalsIgnoreCase("exit")) break;
out.println("S ::: "+input);
System.out.println(input);
}
out.close();
in.close();
fromclient.close();
servers.close();
}
}
If I use Java client I can work with server, but I want to connect to android client. And I found only this library, and I not understand how it work. Examples in site not helped for me.
Make sure you have added its permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Android's kernel, unlike mainline Linux kernel, restricts requests for creating sockets unless that application already has INTERNET permission.
Find more technical information about Android's Paranoid networking option in this link.
UPDATE #1
If you want to connect your Android client to the server on your PC localhost you should not use 127.0.0.1 as server IP address. This is Android its own localhost. You should instead use 10.0.2.2 as server IP address. More Info
#Pavel i've implemented SocketIO client for one of my app
here is the code... i think ..this may help u
private Socket mSocket;
/**
* chat socket connection methods
*/
public void socketConnection()
{
try
{
mSocket = IO.socket(Constant.CHAT_SERVER_URL);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on("message", onSocketConnectionListener);
mSocket.connect();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
new Thread(new Runnable() {
#Override
public void run() {
while(mSocket.connected()==false)
{
//do nothing
}
sendConnectData();
}
}).start();
}
/**
* Send Data to connect to chat server
*/
public void sendConnectData()
{
JSONObject msgToSend=new JSONObject();
try
{
msgToSend.put("Type", 1);
msgToSend.put("userid", userid);
}
catch (Exception e)
{
e.printStackTrace();
}
mSocket.emit("message", msgToSend);
}
/**
* Listener for socket connection error.. listener registered at the time of socket connection
*/
private Emitter.Listener onConnectError = new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mSocket != null)
if (mSocket.connected() == false)
socketConnection();
}
});
}
};
/**
* Listener to handle messages received from chat server of any type... Listener registered at the time of socket connected
*/
private Emitter.Listener onSocketConnectionListener = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// handle the response args
}
});
}
};
I'm doing a mobile app for a website and they use Socket.io and Websocket to comunicate.
I'm using socket.io-java-client on Android to connect to the Socket.io server, the problem is, i don't know how to set custom headers / cookies with it.
here is how the code looks like:
public void runIO(){
try {
SocketIO socket = new SocketIO("http://192.168.1.60:1337");
socket.connect(new IOCallback() {
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
#Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
#Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
#Override
public void onConnect() {
System.out.println("Connection established");
}
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
});
// This line is cached until the connection is establisched.
socket.send("Hello Server!");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In fact there are simple functions that can be used to set headers before connection:
addHeader(String key, String value) and setHeaders(Properties headers)
You can also use SocketIO(final String url, Properties headers) (instead of SocketIO(final String url) that i was using):
// Haeader Properties initiation
private Properties headers = new Properties();
and then for exemple to set cookies:
headers.setProperty("Cookie","key=data;key2=data2");
Finally when connecting replace
this.socket = new SocketIO(val);
by
this.socket = new SocketIO(val,this.headers);