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
}
});
}
};
Related
I am using Apache Mina SSHD to communicate with two Android devices. I have server-side code and client-side I'd like to establish a connection and start streaming data (byte array packet) from server to client and client to server until a button pressed to disconnect. How can I do this?
SERVER
I use this link SSHD SERVER stackOverflow
public void startSSHServer() {
int port = 22;
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(
"src/test/resources/hostkey.ser"));
sshd.setSubsystemFactories(Arrays
.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
sshd.setCommandFactory(new ScpCommandFactory());
sshd.setShellFactory(new ProcessShellFactory(new String[]{"/system/bin/sh", "-i", "-l"})); // necessary if you want to type commands over ssh
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
#Override
public boolean authenticate(String u, String p, ServerSession s) {
return ("sftptest".equals(u) && "sftptest".equals(p));
}
});
try {
sshd.start();
} catch (IOException e) {
e.printStackTrace();
}
}
CLIENT
I use this link SSHD CLIENT geeksforgeeks
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Connection establishment and authentication
try (ClientSession session = client.connect(username, host, port).verify(10000).getSession()) {
session.addPasswordIdentity(password);
session.auth().verify(50000);
System.out.println("Connection establihed");
// Create a channel to communicate
channel = session.createChannel(Channel.CHANNEL_SHELL);
System.out.println("Starting shell");
ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
channel.setOut(responseStream);
// Open channel
channel.open().verify(5, TimeUnit.SECONDS);
try (OutputStream pipedIn = channel.getInvertedIn()) {
pipedIn.write(command.getBytes());
pipedIn.flush();
}
// Close channel
channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED),
TimeUnit.SECONDS.toMillis(5));
// Output after converting to string type
String responseString = new String(responseStream.toByteArray());
System.out.println(responseString);
shellOutput.setText(responseString);
} catch (IOException e) {
e.printStackTrace();
} finally {
client.stop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
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.
Trying to write - distributive simulation framework, where program is represented by an array with moving objects, server send command to move, client answer objects out of array
Goal - server send text message to each connected client separately
- client answer
Problem - can not find a way how to implement server listening and writing to one choosed client
Is there anyone, please, who can help me or get some idea?
private ServerSocket serverSocket;
private ArrayList<BufferedReader> clientBufReaders;
private ArrayList<BufferedWriter> clientBufWriters;
public static void main(String[] args) {
Server server = new Server();
}
public Server() {
try {
this.serverSocket = new ServerSocket(23456);
this.clientBufReaders = new ArrayList<BufferedReader>();
this.clientBufWriters = new ArrayList<BufferedWriter>();
this.clients();
} catch (IOException e) {
e.printStackTrace();
}
}
private void clients() {
Thread acceptThread = new Thread(new Runnable() {
private Scanner in;
public void run() {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
clientBufReaders.add(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
clientBufWriters.add(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
this.in = new Scanner(System.in);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
);
acceptThread.start();
while (true) {
synchronized (clientBufReaders) {
for (BufferedReader in : clientBufReaders) {
try {
if (in.ready()) {
System.out.println(in.readLine());
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
i am making a java socket chat program and i made it compatible for multiple connections and when a user joins it doesn't send the message "[user] Joined" to all clients just to the one that connected but i have a thread for each client if anyone can tell me why it is only sending the message to the user that recently joined i would greatly appreciate it. Here is the server code
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
users.add(s);
new EchoThread(s).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class EchoThread extends Thread {
private Socket sock;
public EchoThread(Socket s) throws IOException {
this.sock = s;
output = new ObjectOutputStream(sock.getOutputStream());
}
public void run() {
System.out.println(sock.getInetAddress() + " Connected");
try {
for(Socket s: users) {
output.writeObject(s.getInetAddress() + " Connected");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server() throws IOException {
Thread t = new Thread(new Accept());
t.start();
}
public static void main(String[] args) throws IOException {
new server();
}
}
So,
Every time someone connects to the server, u create a new EchoThread.
Each User has his own EchoThread.
Your Server role is to manage all the EchoThreads and Sockets.
output.writeObject(s.getInetAddress() + " Connected");
This only sends a message to ONE user.
Your Server should have a List of Sockets and send messages to every Sockets
public ArrayList<Socket> users = new ArrayList<Socket>();
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
users.add(s);
outputs.add(new ObjectOutputStream(s.getOutputStream()));
for (ObjectOutputStream o: outputs) {
o.writeObject(s.getInetAddress() + " has connected");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I'm trying to communicate flash android app to java using sockets, but when the app is connected via 3G - many packages get lost (not received).
Here is my Java server:
public class SServer implements Runnable {
protected int serverPort = 9070;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected List<ClientRunnable> clients = new ArrayList<ClientRunnable>();
protected int msgCounter = 0;
public static void main(String args[]) {
SServer server = new SServer();
new Thread(server).start();
}
public void run(){
//init spam timer
new Timer().schedule(new TimerTask() {
#Override
public void run() {
for (ClientRunnable cr : clients) {
cr.send("Message " + msgCounter++);
cr.send("Message " + msgCounter++);
cr.send("Message " + msgCounter++);
}
}
}, 0, 2000);
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped."); return;
}
throw new RuntimeException("Error accepting client connection", e);
}
ClientRunnable cr = new ClientRunnable(clientSocket);
clients.add(cr);
new Thread(cr).start();
}
System.out.println("Server Stopped.") ;
}
private synchronized boolean isStopped() {
return this.isStopped;
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
System.out.println("Server Started.") ;
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
}
And this is the client thread:
public class ClientRunnable implements Runnable{
protected Socket clientSocket = null;
protected Boolean connected = false;
protected BufferedReader in = null;
protected PrintStream os = null;
public ClientRunnable(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
connected = true;
try {
//InputStream input = clientSocket.getInputStream();
in = new BufferedReader (new InputStreamReader(clientSocket.getInputStream(), "UTF-8" ));
os = new PrintStream(clientSocket.getOutputStream());
//read
//..
} catch (IOException e) {
onError(e);
connected = false;
closeConnection();
}
}
private void closeConnection() {
os.close();
//other closing code..
}
public void send(String data) {
try {
byte[] dataBytes = data.getBytes("UTF-8");
//will contain all bytes plus zery byte flash delimiter
byte[] allBytes = new byte[dataBytes.length + 1];
System.arraycopy(dataBytes, 0, allBytes, 0, dataBytes.length);
allBytes[allBytes.length-1] = (byte)0;
synchronized (this) {
Thread.sleep(50); //non 3G workaround
os.write(allBytes);
os.flush();
}
} catch (Exception e) {
e.printStackTrace();
onError(e);
}
}
public void onError(Exception ex) {
ex.printStackTrace();
}
}
Please note that Thread.sleep(50); before every send write - fixes the problem on non regular non 3G connections. But when the app is runnung on 3G, this value must be much higher and there are still missed pachages sometimes.
Here is my flex client:
<?xml version="1.0" encoding="utf-8"?>
<fx:Script>
<![CDATA[
import spark.events.ViewNavigatorEvent;
private var _socket:Socket;
private var _host:String = "<MY HOST IP>";
private var _port:int = 9070;
protected function onViewActivate(event:ViewNavigatorEvent):void {
_socket = new Socket(_host, _port);
_socket.addEventListener(Event.CLOSE, function(e:Event):void{ ta.appendText("Close\n"); });
_socket.addEventListener(Event.CONNECT, function(e:Event):void{ ta.appendText("Connect\n"); });
_socket.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{ ta.appendText("IO Error\n"); });
_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:IOErrorEvent):void{ ta.appendText("Security Error\n"); });
_socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
}
private function socketDataHandler(event:ProgressEvent):void {
var socket:Socket = event.target as Socket;
var str:String = socket.readUTFBytes(socket.bytesAvailable);
ta.appendText(str+"\n");
}
]]>
</fx:Script>
<s:VGroup width="100%" height="100%">
<s:TextArea id="ta" skinClass="spark.skins.mobile.TextAreaSkin" width="100%" height="100%" />
<s:Button label="Reconnect" click="_socket.connect(_host, _port)" />
</s:VGroup>
And this is how it finally looks like:
(note that the sequenced sendings are problematic, although there is 50ms delay)
As you can see many of the sequencial messages are not received. Increasing the delay helps, but not always (and is bad as solution).
The Flex project is uploaded HERE
The Java project is uploaded HERE
I recently had a similar problem on a socket connection running between AS and Java. I solved it by making a message queue in Java, adding a message ID to my messages and then making the ActionScript side respond with the messageID before the next message in queue is sent. That guaranteed that the same message went out over and over until AS responded that it got it.