I am trying to get my server made on vb.net to send messages to my client made on android. I have a client and server made on vb.net, I can send and receive messages (text) between them without problem. But when I try to make the client work the same on Android, I can not receive messages to the client (android), but if I could get it to send a message to the server (vb.net) .. They are stuck with this, and I do not understand how to continue
SERVER VB.NET
Imports System.Net.Sockets
Imports System.Text
Public Class Servidor
Dim Tcp As TcpListener
Dim th As New Threading.Thread(AddressOf Rutina)
Dim ejecuto = False
Private Sub Servidor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Dim tcpservercliente As New TcpClient
Public Function Rutina()
Try
Do
If ejecuto = True Then
Exit Do
End If
If Tcp.Pending = True Then
tcpservercliente.Client = Tcp.AcceptSocket
End If
If tcpservercliente.Available > 0 Then
Dim databytes(1000) As Byte
Dim decode As New ASCIIEncoding
tcpservercliente.Client.Receive(databytes)
txtRecibido.Text += vbCrLf & "Cliente Android: " & decode.GetString(databytes)
End If
Loop
Catch ex As System.InvalidOperationException
MsgBox("Error: " & ex.Message)
End Try
End Function
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Try
Tcp = New TcpListener(System.Net.IPAddress.Parse("192.168.1.8"), 1371)
Tcp.Start()
th.Start()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Servidor_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
th.Abort("Rutina")
Application.Exit()
End Sub
Private Sub btnEnviar_Click(sender As Object, e As EventArgs) Handles btnEnviar.Click
Try
Dim decode As New ASCIIEncoding
tcpservercliente.Client.Send(decode.GetBytes(txtMensajeEnviar.Text))
Catch ex As System.Net.Sockets.SocketException
MsgBox(ex.Message)
End Try
End Sub
CLIENT ANDROID
//CLASS RM
public class RM extends AsyncTask<Void, Void, Void> {
Socket socket;
BufferedReader input;
#Override
protected Void doInBackground(Void... voids) {
try {
socket = new Socket("192.168.1.8",1371);
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
input = new BufferedReader(streamReader);
if(input.ready()){
Log.i("AsyncTask", "Ready ");
}else{
Log.i("AsyncTask", "No Ready");
}
input.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
//VOID MAIN ACTIVITY
RM mr = new RM();
mr.execute();
The times I've tried to see that it returns, it's always empty. The message that is being sent from the server is not arriving
Sorry my bad english
==========================================
EDIT:
This is the class I use to send messages from the client (android) to the server (vb.net)
package com.example.app_test_client;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MessageSender extends AsyncTask<String, Void, Void> {
Socket socket;
PrintWriter pw;
#Override
protected Void doInBackground(String... voids) {
String mensaje_enviar = voids[0];
try {
socket = new Socket("192.168.1.8",1371);
pw = new PrintWriter(socket.getOutputStream());
pw.write(mensaje_enviar);
pw.flush();
pw.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
CODE MAIN ACTIVITY (CLIENT ANDROID)
package com.example.app_test_client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
EditText mensaje_enviar;
TextView mensaje_recibido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mensaje_enviar = (EditText)findViewById(R.id.txtTexto);
mensaje_recibido = (TextView)findViewById(R.id.lblMensaje);
}
public void enviar(View v){
MessageSender MensajeRemitente = new MessageSender();
MensajeRemitente.execute(mensaje_enviar.getText().toString());
}
}
The void "enviar" I have it in the "onClick" button. All this to send messages from the client (android) to the server (vb.net) works for me.
Based on this class "MessageSender", I made another equal to receive messages on the client (android) but it has not worked
If you are trying to receive the message in the Android device, then you are missing reading the message itself with String messageReceived = input.readLine();. Your code would look like this:
...
socket = new Socket("192.168.1.8",1371);
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
input = new BufferedReader(streamReader);
String messageReceived = input.readLine();
...
You will have the message sent from the server in messageReceived.
EDIT
Without getting into much details, when you read the data sent from the server, you need to know when the data sent "ends", and the easiest way you have with your current implementation is to print a "line end" (a vbCrLf character in VB) when you send the message. Thus, in your Sub btnEnviar_Click you need to add a vbCrLf as follows:
tcpservercliente.Client.Send(decode.GetBytes(txtMensajeEnviar.Text & vbCrLf))
Additional notes
When data is being read from the server the socket needs to know when the data ends. There are several ways of achieving this, but the easiest way is in your case is to read "a line ending" with String messageReceived = br.readLine();. If the server doesn't send any "line end" (as in your current implementation), it will keep waiting for it and hence it appears that the programs hungs. That is what is happening in your case when you note that you cannot do anything else after reading the message - it is just waiting for something that will never come.
It is not necessary that you check input.ready() when reading from the server. This will only be true when the data has been completely sent from the server, and there is a great chance that the data is still being sent when it is invoked.
If you want to know better how TCP sockets works, this SO question has good examples that you can try.
Related
I've come across an issue when sending an object over a local connection. The object will send the first time as expected. However variables of the object are constantly being changed therefore need to be updated when sending to the other connection. This is done through sending messages prompting the other client to listen and wait for the object being sent.
I'm aware that the java.io.ObjectOutputStream.reset() method exists but keep getting the following error:
error: cannot find symbol
output.reset();
Here's how the code is currently structured (Minus lots of non relevant code):
import java.net.*;
import java.util.*
import java.io.*;
public class Client
{
private static Socket cSocket = null;
private static ObjectOutput output = null;
private static Person myPerson = null;
private static String serverHost = "localhost";
public void Run()
{
// Declaring the output
output = new ObjectOutputStream(
cSocket.getOutputStream()
);
}
private static void sendPerson()
{
try
{
output.writeObject( myPerson );
output.reset();
} catch (Exception e)
{
}
}
}
TLDR: Each time sendPerson() is called the other client receives the first object sent to the other client rather than the updated variables. Tried using reset(); but error is thrown.
Would just like the objects updated variables to be sent rather than the initial object always being sent.
To use ObjectOutputStream#reset you have to define your field with such type.
Not ObjectOutput, but ObjectOutputStream.
Like this:
private static ObjectOutputStream output = null;
I am trying to make a UDP Listener listening to a server and receiving data.
Here is the UDPListener :
public class UDPListener extends AsyncTask<Void, String, Void>{
public UDPConnector udpConnector;
public UDPListener(UDPConnector udpConnector){
byte[] buff;
this.udpConnector = udpConnector;
System.out.println("UDPListener initalized");
}
#Override
protected Void doInBackground(Void... voidResult){
Looper.prepare();
while(true){
byte[] buffer = new byte[512];
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
try {
System.out.println("Message reçu debug ");
udpConnector.UDPSocket.receive(p);
if(p.getData().length > 0){
buffer = p.getData();
String s = new String(buffer, 0, p.getLength());
publishProgress(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
udpConnector.main.handleTextReceived(values[values.length-1]);
}
}
The problem is publishProgress() never gets executed. I am sure that the UDPConnector is well configured because i can send data to the server. And i know that the method doInBackground is executed. I am also sure that the serveur is sending data to me as i can receive it with other tools.
I can post more code if needed, please let me know.
Thanks
If you are using the phone emulator, the emulator might be changing your expected IP address for which you will have to create a redirect.
Look at this post
Datagram (UDP) receiver not working - not receiving broadcast packets
So, you don't initialize the socket with a specific port? which one is your server using for sending the datagrams? Maybe your problem is, that the socket is listening to a random port, which does not match to your port.
Im working on building my own GUI program that talks to my pc from a tablet. I have the server side done in java but my problem is on the client side.
I want to send data out the PrintWriter to the server from a separate method.
I have accomplished sending in the code below (it sends 'a') but i cant figure out how to send it from a separate method. i believe its a basic java scope problem that im not understanding. i would really appreciate the help.
I have tried moving the variables into other scopes.
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) {
String hostName = "192.168.0.3";
int portNumber = 6666;
try ( //Connect to server on chosen port.
Socket connectedSocket = new Socket(hostName, portNumber);
//Create a printWriter so send data to server.
PrintWriter dataOut = new PrintWriter(connectedSocket.getOutputStream(), true);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
//Send data to server.
dataOut.println("a");
}catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
public static void sendToServer() {
//I want to control the print writer from this method.
//I have failed i all the ways i have tried.
}
}
You could move the Printer-Code (try try block) into the sendToServer-method and call it via
TestClient client = new TestClient();
client.sendToServer("this is a test");
Of course the sendToServer method needs to accept a parameter then. Even better would probably be to put the main method into a Starter class and decouple it from the Client-Class that you use for sending the data.
I'm trying to use SSL with IMAP in java. I do not want to use the IMAP class.
For some reason, when I send the n th message, I receive the answer to message n-2, and not to message n-1. Which means that I don't receive any answer to the first message sent until I send the second message. Can anyone spot what's wrong in the following minimal code ? (It is indeed minimal, apart from the println, which, I guess, help debugging)
import java.io.*;
import javax.net.ssl.*;
public class Mail{
static String server = "imap.gmail.com";
static String user = "straightouttascript#gmail.com";
static String pass = "azerty75";
public static void print (PrintWriter to, String text){
System.out.println("sent : "+text);
to.println(text+ "\r");
to.flush();
}
public static void read (BufferedReader from) throws InterruptedException, IOException {
do {
String line = from.readLine();
System.out.println("received: "+line);
} while (from.ready());
}
public static void main(String[] args){
try{
SSLSocket sslsocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(server, 993);
System.out.println("Start connexion");
BufferedReader from = new BufferedReader(new InputStreamReader(sslsocket.getInputStream()));
// read(from);
PrintWriter to = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sslsocket.getOutputStream())), true);
print(to,"a1 login "+user+" "+pass);
read(from);/*exepcted:
OK gimap ready
a1 OK login#host authenticated (Success)*/
sslsocket.close();
System.out.println("End connexion");
}
catch (Exception e){
e.printStackTrace();
}
}
}
IMAP is not a pingpong protocol. The server doesn't send one line in response to one of yours.
Rather, you send commands and the server sends information. The server is permitted to send you more information than you asked for, so you can get seven responses to one command, and you can even get a response without sending a command at all, which is then called an unsolicited response. Strange phrase. Unsolicited responses are used by some servers to notify you about new mail, by more to notify you about flag changes on messages, and by (almost?) all to notify you that they're about to close your connection.
I've done some searching and it doesn't seem like there is much in the way of success in establishing a tcp/ip socket connection successfully via Coldfusion. I'm trying to act as a simple client and send a string over and get a response. Adobe's EventGateway requires server-side setup, which I can't touch, but also appears to be a listener only (according to Adobe's doc, "It can send outgoing messages to existing clients, but cannot establish a link itself.").
There is another example on SO/cflib.org that is the prevailing post over the web invoking Java objects, but I'm not succeeding with it and it seems pretty much everyone else has some degree of trouble with it. In my attempts, I can get it to init/connect a socket, but nothing else. If I try to send a string, the CF page loads fine but the server side seemingly never sees anything (but will log or note a connection/disconnection). If I try to read a response, the page will never load. If I close the server while it's trying, it will show a connection reset while trying readLine(). I have tried this with an in-house app as well as a simple Java socket listener that will send a message on connect and should echo anything sent.
Is this just not a job for CF? If not, any other simple suggestions/examples from the jQuery/Ajax realm?
Java listener app:
package blah;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
class SocketServer extends JFrame
implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton button;
JLabel label = new JLabel("Text received over socket:");
JPanel panel;
JTextArea textArea = new JTextArea();
ServerSocket server = null;
Socket client = null;
BufferedReader in = null;
PrintWriter out = null;
String line;
SocketServer(){ //Begin Constructor
button = new JButton("Click Me");
button.addActionListener(this);
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add("North", label);
panel.add("Center", textArea);
panel.add("South", button);
} //End Constructor
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == button){
textArea.setText(line);
}
}
public void listenSocket(){
try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
try{
client = server.accept();
//Show connection status in text box, and send back to client
line = " Connected ";
out.println(line);
textArea.setText(line);
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
while(true){
try{
//Try to concatenate to see if line is being changed and we're just not seeing it, show in textbox
line = line + " " + in.readLine();
textArea.setText(line);
//Send data back to client
out.println(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
protected void finalize(){
//Clean up
try{
in.close();
out.close();
server.close();
} catch (IOException e) {
System.out.println("Could not close.");
System.exit(-1);
}
}
public static void main(String[] args){
SocketServer frame = new SocketServer();
frame.setTitle("Server Program");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
}
}
CF Simple Send (minus HTML header/footer, IP to be hard-coded, port on simple listener = 4444):
<cfset sock = createObject( "java", "java.net.Socket" )>
<cfset sock.init( "ip.ip.ip.ip", 4444)>
<cfset streamOut = sock.getOutputStream()>
<cfset output = createObject("java", "java.io.PrintWriter").init(streamOut)>
<cfset streamOut.flush()>
<cfset output.println("Test Me")>
<cfset output.println()>
<cfset streamOut.flush()>
<cfset sock.shutdownOutput()>
<cfset sock.close()>
Simple CF Read (again, minus header/footer template, IP of server to be hard-coded, port 4444)
<cfset sock = createObject( "java", "java.net.Socket" )>
<cfset sock.init( "ip.ip.ip.ip", 4444)>
<cfset streamInput = sock.getInputStream()>
<cfset inputStreamReader= createObject( "java", "java.io.InputStreamReader").init(streamInput)>
<cfset input = createObject( "java", "java.io.BufferedReader").init(InputStreamReader)>
<cfset result = input.readLine()>
<cfset sock.shutdownInput()>
<cfset sock.close()>
I've tried adding some sleeps here and there and also have tried a send not using PrintWriter/using just ObjectOutputStream and writeObject() , but same behavior. Any help would be greatly appreciated. Thanks!
This is going to be a very challenging process to implement in ColdFusion, even when taking advantage of Java, for the simple reason of:
Socket communication is real-time, while web requests have finite starting and stopping points.
For example, when you make a ColdFusion template request, everything (variables, shared memory, object instantiation, etc.) lives within the context of the page request--and (barring a few caveats) dies when the page request ends. So, let's assume for the moment that you had a CFML template that performed the following tasks when requested:
Opened a socket.
Established a connection to a remote ip:port.
Listened for a response.
Printed that response to the browser.
Let's assume further that your code is up-and-running, tested, and working. You are able to open the socket, connect to a remote ip and port (you actually see the incoming request on the remote server, and can confirm this) and for all intents and purposes...your connection is good.
Then, 10 minutes after you executed your CFML page, the remote server sent a string of text over the connection...
...there is nothing on your CFML end that is alive and awaiting that response, ready to print it to the browser. The objects that you instantiated, used to open a socket, and connect...have all gone away, when the CFML template request ended.
This is why (as stated above) when you tried to "read a response", you observed that the page never loaded. What's happening is that ColdFusion is being told "stand by please, we could actually maybe possibly get some data over this socket"...so it blocks the web request from ending and waits...which manifests to the user as what appears to be a "hung" web page.
The nature of real-time socket communication is that it is connected and listening, waiting for a response...and unfortunately, a running web-page cannot run (and 'wait') forever, it will eventually timeout.
The bottom line is that while Java will allow you to open / connect / send / receive / close raw sockets, doing so from within the context of a CFML page may not be the approach you are ultimately looking for.