I have created a client and a server, which both work fine and have no trouble connecting. Now I would like to be able to connect from my android phone to the server. I have imported the kryonet library and copy-pasted the client code into a new android project. The code gave me some errors, but I fixed those. When I tried testing my app, it didn't give me any errors, but my server wasn't getting any connections either. I looked a bit in the LogCat logs, and found out it keeps sticking at "Connecting..". I am totally stuck. This is my android code:
public void openSocket(View view){
Log.i(TAG, "test1");
EditText portText= (EditText)findViewById(R.id.port);
String parts[] = portText.getText().toString().split(":");
partIP = parts[0];
String partPort = parts[1];
port = Integer.parseInt(partPort);
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
connect();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = "Android";
client.sendTCP(packet);
}
And this is my normal client code:
public static void main(String[] args) {
try {
client = new Client();
client.start();
register();
pHandler = new PacketHandler();
new Main();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void register() {
client.getKryo().register(Packet.class);
client.getKryo().register(Packet1Connected.class);
client.getKryo().register(String.class);
client.getKryo().register(String[].class);
client.getKryo().register(Object[].class);
}
public Main() {
try {
connect();
Thread t = new Thread(this);
t.start();
} catch (Exception e) {
pHandler.checkException(e);
}
}
public static void connect() {
try {
String IP = "*MY IP*:25565";
String[] Ip = IP.split(":");
String ipFinal = Ip[0];
int port = Integer.parseInt(Ip[1]);
client.connect(5000, ipFinal, port, port);
} catch (IOException e) {
try {
Thread.sleep(15000);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
System.out.println("Trying to connect.");
connect();
}
Packet1Connected packet = new Packet1Connected();
packet.id = System.getProperty("user.name");
client.sendTCP(packet);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(3000);
if (!client.isConnected())
connect();
} catch (InterruptedException e) {
pHandler.checkException(e);
}
}
}
}
So this:
client.connect(5000, ipFinal, port, port);
is the line it gets stuck on, on android. The normal client just connects normally.
Now my question is, is there something wrong with my android code, or is it just the device, or wifi connection?
If it helps, I tried testing it on my samsung galaxy nexus, which is rooted.
Thanks in advance.
Related
I've created a java server app which opens connections with serverSocket on port 3000 and it works perfectly with java client app I created. But now I started developing client app in react native and I can't understand it's socket API, because socket.io in react native forces me to use WebSocket way.
Is there any other way?
public static final int PORT = 3000;
private ServerSocket mServerSocket = null;
#Override
public void run() {
try {
mServerSocket = new ServerSocket(PORT);
} catch (IOException e) {
close();
return;
}
while (isOpen()) {
try {
mSocket = mServerSocket.accept();
ClientThread clientThread = new ClientThread(new Client(mSocket, this));
mClients.add(clientThread);
clientThread.start();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
try {
mServerSocket.close();
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am new to signalR, tried to connect to a hub and got a connectionId after successful connection.
my code
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "url";
HubConnection connection = new HubConnection(host);
HubProxy hub = connection.createHubProxy("pttdashboardhub");
ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
SignalRFuture<Void> signalRFuture = connection.start(clientTransport);
try {
signalRFuture.get();
System.out.println(connection.getConnectionId());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
hub.on("onEvent",
new SubscriptionHandler1<String>() {
#Override
public void run(String s) {
System.out.println("================ "+s);
}
}, String.class);
server code
var eventHub = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
var result = eventHub.Clients.Group("pttdashboard").onEvent(data);
the problem comes when hub.on function executes i get nothing from the server.
Any help is appreciated.
You can use subscribe function instead of on function.
hub.subscribe("onEvent").addReceivedHandler(new Action<JsonElement[]>(){
#Override
public void run(JsonElement obj) {
System.out.println("================ "+s);
}
});
I hope this helps you.
Hallo I need to write a very simple app that sends and retrieve data trough an UDP link (on Android OS, API level > 18):
This's a piece of code I used in an application I wrote sometime ago to connect trough TCP/IP (and doing the same thing):
class LinkReader implements Runnable
{
private final int mPort;
private final String mAddress;
private final Socket mLinkSocket;
public LinkReader(String address, int port, Socket link_socket)
{
mLinkSocket = link_socket;
mPort = port;
mAddress = address;
}
#Override
public void run()
{
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(
mLinkSocket.getInputStream()
)
);
while (true)
{
Thread.sleep(100);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class LinkThread implements Runnable {
private final int mPort;
private final String mAddress;
private Socket mLinkSocket;
public LinkThread(String address, int port, Socket socket)
{
mLinkSocket = socket;
mPort = port;
mAddress = address;
}
#Override
public void run()
{
try
{
mLinkSocket = new java.net.Socket(
InetAddress.getByName(mAddress),
mPort
);
new Thread(new LinkReader(mAddress,mPort,mLinkSocket)).start();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void sendCommand(String cmd, Socket socket)
{
try
{
PrintWriter _out = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()
)
),
false
);
_out.print(cmd);
_out.flush();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I've not been able to find an example about UDP connection on Android OS and I tought to reuse this code mainly because it was working pretty good (but I have to admint that I had not a very deep knowlede of Android neither I had very hight performances expectations from this piece of code).
Besides it was working in my past application my question is it correct now, in terms of code structure and aging?
How can I modify this to establish an UDP connection?
BTW Up to now I don't need really a R/W connection (I just need to send commands over there).
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'm having issues sending objects to a server. Right now, I have a server setup and listening for clients. The client connects, sends a test object (just a String) and outputs it to the command line. It works for the first string sent but none after that.
Server (Hivemind.java):
// Open server socket for listening
ServerSocket ss = null;
boolean listening = true;
try {
ss = new ServerSocket(PORT_NUMBER);
} catch (IOException e) {
System.err.println("Cannot start listening on port " + PORT_NUMBER);
e.printStackTrace();
}
// While listening is true, listen for new clients
while (listening) {
Socket socket = ss.accept();
ServerDispatcher dispatcher = new ServerDispatcher(socket);
dispatcher.start();
}
// Close the socket after we are done listening
ss.close();
Server Thread (ServerDispatcher):
public ServerDispatcher(Socket socket) {
super("ServerDispatcher");
this.socket = socket;
}
public void run() {
System.out.println("Client connected");
try {
input = socket.getInputStream();
objInput = new ObjectInputStream(input);
Object obj = null;
try {
obj = (String)objInput.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(obj);
} catch (IOException ex) {
Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
}
Connection Class (HivemindConnect.java):
public HivemindConnect(int port) {
this.port = port;
url = "localhost";
}
public HivemindConnect(int port, String url) {
this.port = port;
this.url = url;
}
public void connect() {
try {
socket = new Socket(url, port);
output = socket.getOutputStream();
objOutput = new ObjectOutputStream(output);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
try {
objOutput.close();
output.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(Object obj) {
try {
objOutput.writeObject(obj);
objOutput.flush();
} catch (IOException ex) {
Logger.getLogger(HivemindConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}
CustomerTopComponent:
// When the TC is opened connect to the server
#Override
public void componentOpened() {
hivemind = new HivemindConnect(9001);
hivemind.connect();
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
hivemind.send(txtText.getText());
}
// When the TC is closed close the connection to the server
#Override
public void componentClosed() {
hivemind.close();
}
You need a loop like this:
while(objInput.available()>0){
Object obj = null;
obj = (String)objInput.readObject();
System.out.println(obj);}
Or something similar.