I am creating a socket connection with a client utilizing android studio. I can successfully make a connection between the mobile device and the server, and my first debug message (Log.d("While Debugger", line)) successfully shows the input data from the server. However, the arraylist does not appear to adding the results, and my other debug messages are not providing any output!
To clarify further, when I call the returnData() method the temperature array is returned as null.
Any help will be much appreciated, and I will do my best to answer any questions asked of what I've written. Thanks!
package com.mycompany.myfirstapp;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by seank on 15/07/2015.
*/
public class SocketExample {
ArrayList<Double> temperature = new ArrayList<Double>();
public SocketExample() throws IOException {
String serverHostname = new String ("192.168.1.143");
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10007.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
Log.d("Here", "Got to the streams");
try {
echoSocket = new Socket(serverHostname, 10007);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
Log.e("Here","Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
Log.e("Here","Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
String line;
while( (line = in.readLine()) != null ) {
Log.d("While Debugger", line);
Double value = Double.parseDouble(line);
temperature.add(value);
}
if(temperature.size() == 0) {
Log.d("Numbers", "size = 0");
}
else {
Log.d("Numbers", String.valueOf(temperature.size()));
}
if(String.valueOf(temperature.size()) == null) {
Log.e("Numbers", "The temperature size is a null value");
}
// Close our streams
in.close();
out.close();
echoSocket.close();
}
public ArrayList<Double> returnData() {
return temperature;
}
public static void main(String[] args) throws IOException {
SocketExample socket = new SocketExample();
}
}
I think that, your program is blocking in the while loop, so your next debug is not executed.
You can try to add below code into the your while loop
if(temperature.size() == 0) {
Log.d("Numbers", "size = 0");
}
else {
Log.d("Numbers", String.valueOf(temperature.size()));
}
Related
I am using C# to create a client socket that should connect with a Java socket server. But no matter what I try the code always manages to send some sort of message, but for the Java server it's completely empty.
This is the C# client code:
using Godot;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Scanning: Control
{
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
string toSend = "Handshake:Interface";
IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 429);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(serverAddress);
// Sending
int toSendLen = System.Text.Encoding.ASCII.GetByteCount(toSend);
byte[] toSendBytes = System.Text.Encoding.ASCII.GetBytes(toSend);
byte[] toSendLenBytes = System.BitConverter.GetBytes(toSendLen);
clientSocket.Send(toSendLenBytes);
clientSocket.Send(toSendBytes);
Console.WriteLine("Client received: " + rcv);*/
clientSocket.Close();
}
}
Java code that is responsible for working with the client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ClientHandler {
public PrintWriter out;
public BufferedReader in;
public Socket clientSocket;
public Thread thread;
public ClientHandler(Socket client) {
clientSocket = client;
System.out.println("Processing connection from " + clientSocket.getInetAddress());
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
ArrayList<String> cmdBuffer = new ArrayList<String>();
while (!Main.test.get()) {
String msg = in.readLine();
if(msg.startsWith("Handshake")) {
System.out.println("LOG: " + msg);
String[] work = msg.split(":");
if (!MessageChannel.clients.contains(work[1])) {
respond("1/I/Handshake successful for/" + work[1]);
respond("Connected: " + MessageChannel.clients);
MessageChannel.buffer.put(work[1], cmdBuffer);
MessageChannel.clients.add(work[1]);
}
} else if (msg.startsWith("Disconnect")) {
System.out.println("LOG: " + msg);
String[] work = msg.split(":");
MessageChannel.clients.remove(work[1]);
MessageChannel.buffer.remove(work[1]);
out.println("I/Disconnected/" + work[1]);
} else if(msg.startsWith("List")) {
System.out.println("LOG: " + msg);
respond("0/Connected: " + MessageChannel.clients);
} else {
String[] work = msg.split(":");
if (MessageChannel.clients.contains(work[0])){
if (work[1].equals("Lookup")) {
out.println(MessageChannel.buffer.get(work[0]).size() +"/Lookup:");
for (String e : MessageChannel.buffer.get(work[0])) {
out.println(e);
}
MessageChannel.buffer.replace(work[0], new ArrayList<String>());
} else {
System.out.println("LOG: " + msg);
MessageChannel.buffer.get(work[1]).add(work[2]);
respond("0/I/Success");
}
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
thread.start();
}
public void respond(String msg) {
out.println(msg);
System.out.println("LOGR: " + msg);
}
}
How can I fix that? Thanks in advance!
I am attempting to send a BufferedImage over a socket sever to another client. Ill post my code below. When I run the server and the connect to the server with the sending client, and receiving client, everything just sits there. The server shouldn't even be receiving anything unless it has already printed "name is attempting to connect to: " which it doesn't it just sits there. I don't know why it doesn't do anything at all.
Client that sends: http://pastebin.com/X4z55Hdp
Client that receives: http://pastebin.com/MB9qEyGy
Server Source that sends and recieves:
package core;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import utilities.Tools;
public class Node implements Runnable {
private String name;
private Socket socket;
private boolean isApp;
public Node(Socket s, String name) {
this.setName(name);
this.setSocket(s);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Socket getSocket() {
return socket;
}
public void setSocket(Socket socket) {
this.socket = socket;
}
public void run() {
while (true) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true);
if (in.readLine() != null) {
// Tools.log("[INPUT] " + in.readLine());
String i = in.readLine();
if (i.contains("set name ")) {
String n = i.replace("set name ", "");
Tools.log("Changing " + name + " to " + n);
this.name = n;
if (n.contains("_app")) {
this.isApp = true;
}
} else {
String toFind = name + "_app";
if (isApp)
toFind = name.replace("_app", "");
Tools.log(name + " is attempting to connect to: "
+ toFind);
for (Node n : Server.nodes) {
if (n.getName().equals(toFind)) {
Tools.log(n.getName() + " found, sending data");
ObjectOutputStream outToNode = new ObjectOutputStream(
n.getSocket().getOutputStream());
ObjectInputStream inFromClient = new ObjectInputStream(
socket.getInputStream());
BufferedImage img = (BufferedImage) inFromClient
.readObject();
if (img != null) {
outToNode.writeObject(img);
}
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The BufferedImage must be serialized. You can convert the image in to a byte array and once it reads the byte array, convert it back in to an image.
The sender is undoubtedly getting a NotSerializableException when calling writeObject() with a BufferedImage, because BufferedImage doesn't implement Serializable. Therefore you can't get one from a readObject() call either. You'll have to turn the BufferedImage into bytes for sending, and back again when receiving. Have a look at javax.imageio for one way to do this.
So, basically it works, but it doesn't. It doesn't throw any errors, it just doesn't finish writing the file. It does read all of the lines in the file and they are all formatted correctly. I've tried debugging all of that. When debugging the "currentLine" all of the lines show up and are formatted correctly; However if I check my file that I'm writing to, it writes some of them perfectly, and then will just cut off at the end. Like the program didn't have enough time before killing itself.
My guess would be that writing takes awhile, and the program is being terminated before the file finishes writing, if that's the case, how can I avoid that?
Here's the code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
BufferedReader fileReader;
BufferedWriter fileWriter;
private Main() {
try {
fileReader = new BufferedReader(new FileReader("File/spawn-config.cfg"));
fileWriter = new BufferedWriter(new FileWriter("Dumped/world_npcs.json"));
loadFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadFile() {
String currentLine;
try {
fileWriter.write("[\n");
while((currentLine = fileReader.readLine()) != null) {
if(!currentLine.startsWith("//") && !currentLine.startsWith("[")
&& !currentLine.startsWith("/*")) {
System.err.println(currentLine);
String[] array = currentLine.split("\\t");
String npcID = array[0].substring(7);
String xPos = array[1];
String yPos = array[2];
String zPos = array[3];
String walk = "false";
String radius = "0";
//-----------------------
fileWriter.write("{\n");
fileWriter.write("\"npc-id\": "+npcID+"\n");
fileWriter.write("\"position\": {\n");
fileWriter.write("\"x\": " + xPos + "\n");
fileWriter.write("\"y\": " + yPos + "\n");
fileWriter.write("\"z\": " + zPos + "\n");
fileWriter.write("},\n");
fileWriter.write("\"walking-policy\": {\n");
fileWriter.write("\"coordinate\": false, \"radius\": 0\n");
fileWriter.write("}\n},");
}
}
fileWriter.write("]");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] params) {
new Main();
}
}
If you are ready with writing flush and close the outputstream
fileWriter.flush();
fileWriter.close();
I am planning to do a java onvif application. I have created a new project and generated sources from devicemgmt.wsdl.Also generated the classes from remote discovery.wsdl.
How can I discover a device in a network using theses generated classes?
Thanks for any help.
devicemgmt.wsdl is not related to discovery process, the ONVIF discovery process is based on http://specs.xmlsoap.org/ws/2005/04/discovery it use SOAP over UDP.
If you are using apache-cxf, this can be achieve using
org.apache.cxf.ws.discovery.WSDiscoveryClient
A simple sample code could be :
import java.util.List;
import javax.xml.ws.EndpointReference;
import org.apache.cxf.ws.discovery.WSDiscoveryClient;
public class Main
{
public static void main(String[] args)
{
WSDiscoveryClient client = new WSDiscoveryClient();
client.setVersion10(); // use WS-discovery 1.0
client.setDefaultProbeTimeout(1000); // timeout 1s
System.out.println("Probe:" + client.getAddress());
List<EndpointReference> references = client.probe();
System.out.println("Nb answsers:" + references.size());
for (EndpointReference ref : references)
{
System.out.println(ref.toString());
}
}
}
I had the same problem, CXF is simply to big, please check my approach: JavaWsDiscovery at https://github.com/thhart/javaWsDiscovery.
It uses a simple network probe as suggested by Onvif standards to be able to identify any devices on your local network, following line will return you all available devices:
final Collection urls = DeviceDiscovery.discoverWsDevicesAsUrls("^http$", ".onvif.");
Simple and complete example pure Java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author Ronald
*/
public class TestDiscoveryPureJava {
public static void main(String cor[]) throws SocketException{
discoverWsDevices();
}
public static void discoverWsDevices() throws SocketException {
final int WS_DISCOVERY_PORT = 3702;
final String WS_DISCOVERY_ADDRESS_IPv4 = "239.255.255.250";
Thread thread = new Thread() {
#Override
public void run() {
final String probe = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">\n" +
" <s:Header>\n" +
" <a:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action>\n" +
" <a:MessageID>uuid:f0ded492-301a-4891-882b-cb2d7cac2e45</a:MessageID>\n" +
" <a:ReplyTo>\n" +
" <a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>\n" +
" </a:ReplyTo>\n" +
" <a:To s:mustUnderstand=\"1\">urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To>\n" +
" </s:Header>\n" +
" <s:Body>\n" +
" <Probe xmlns=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\">\n" +
" <d:Types xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:dp0=\"http://www.onvif.org/ver10/network/wsdl\">dp0:Device</d:Types>\n" +
" </Probe>\n" +
" </s:Body>\n" +
"</s:Envelope>";
DatagramSocket datagramSocket = null;
try {
datagramSocket = new DatagramSocket();
datagramSocket.setBroadcast(true);
datagramSocket.setSoTimeout(9000);
} catch (SocketException e) {
System.out.println( "In discoverWsDevices datagram socket exception" + datagramSocket);
e.printStackTrace();
}
byte[] soapMessageByteArray = probe.getBytes();
DatagramPacket datagramPacketSend = null;
try {
datagramPacketSend = new DatagramPacket(
soapMessageByteArray,
soapMessageByteArray.length,
InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4),
WS_DISCOVERY_PORT);
} catch (UnknownHostException e) {
System.out.println("Unknown host in send packet");
e.printStackTrace();
}
try {
System.out.println("Send package");
datagramSocket.send(datagramPacketSend);
System.out.println("package sent");
} catch (IOException e) {
System.out.println("In discoverWsDevices datagram socket IOException send " + datagramSocket);
e.printStackTrace();
}
System.out.println("Sending data");
System.out.println(datagramPacketSend.getAddress().getHostName()+":"+WS_DISCOVERY_PORT);
List<ByteArrayInputStream> probeMatches = new ArrayList<>();
while (true) {
byte[] responseMessageByteArray = new byte[9000];
DatagramPacket datagramPacketRecieve = new DatagramPacket(responseMessageByteArray,responseMessageByteArray.length);
try {
System.out.println("Waiting response...");
datagramSocket.receive(datagramPacketRecieve);
} catch (SocketTimeoutException e) {
datagramSocket.close();
System.out.println("In discoverWsDevices datagram socket timeout exception");
break;
} catch (IOException e) {
System.out.println("In discoverWsDevices datagram socket ioexception");
e.printStackTrace();
break;
}
probeMatches.add(new ByteArrayInputStream(datagramPacketRecieve.getData(), 0, datagramPacketRecieve.getLength()));
}
for (ByteArrayInputStream input : probeMatches) {
byte[] bytes = new byte[input.available()];
input.read(bytes, 0, input.available());
String stream = new String(bytes);
System.out.println("stream" + stream);
}
}
};
thread.start();
}
}
How to implement SCTP protocol between a gateway and a server with java ?
If your target is Java 7 never try to implement it. As Andrew and Tom stated its already implemented as a core feature.
No need, just use sctp:
https://github.com/RestComm/sctp
Handles most needs, works great.
Windows cannot support SCTP. if want to does with windows plz install sctp driver.Other wise use linux am adding simple client server example
Client.java
package mai;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
public class Client
{
public static void main(String[] args)
{
try {
//SocketAddress socketAddress = new InetSocketAddress( 6050);
InetSocketAddress socketAddress = new InetSocketAddress("192.9.200.193", 4444);
System.out.println("open connection for socket [" + socketAddress + "]");
SctpChannel sctpChannel = SctpChannel.open(socketAddress, 1,1); //(socketAddress, 1 ,1 );
sctpChannel.bind(new InetSocketAddress(4444)); //6060
sctpChannel.connect(socketAddress, 1 ,1);
System.out.println("sctpChannel.getRemoteAddresses() = " + sctpChannel.getRemoteAddresses());
System.out.println("sctpChannel.getAllLocalAddresses() = " + sctpChannel.getAllLocalAddresses());
System.out.println("sctpChannel.isConnectionPending() = " + sctpChannel.isConnectionPending());
System.out.println("sctpChannel.isOpen() = " + sctpChannel.isOpen());
System.out.println("sctpChannel.isRegistered() = " + sctpChannel.isRegistered());
System.out.println("sctpChannel.provider() = " + sctpChannel.provider());
System.out.println("sctpChannel.association() = " + sctpChannel.association());
System.out.println("send bytes");
final ByteBuffer byteBuffer = ByteBuffer.allocate(64000);
//Simple M3ua ASP_Up message
byte [] message = new byte []{1,0,3,1,0,0,0,24,0,17,0,8,0,0,0,1,0,4,0,8,84,101,115,116};
final MessageInfo messageInfo = MessageInfo.createOutgoing(null, 0);
System.out.println("messageInfo = " + messageInfo);
System.out.println("messageInfo.streamNumber() = " + messageInfo.streamNumber());
byteBuffer.put(message);
byteBuffer.flip();
sctpChannel.send(byteBuffer, messageInfo);
System.out.println("close connection");
sctpChannel.close();
System.in.read();
} catch (Exception e) {
e.printStackTrace();
try {
System.in.read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Server.java
package mai;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpServerChannel;
public class Server {
static ByteBuffer rxBuffer;
public static void main(String[] args)throws Exception {
rxBuffer = ByteBuffer.allocateDirect(64000);
rxBuffer.clear();
rxBuffer.rewind();
rxBuffer.flip();
// SctpChannel xx=SctpChannel.open();
com.sun.nio.sctp.SctpChannel sc = com.sun.nio.sctp.SctpChannel.open();
SocketAddress serverSocketAddress = new InetSocketAddress(4444);
System.out.println("create and bind for sctp address");
SctpServerChannel sctpServerChannel = SctpServerChannel.open().bind(serverSocketAddress);
System.out.println("address bind process finished successfully");
SctpChannel sctpChannel;
while ((sctpChannel = sctpServerChannel.accept()) != null) {
System.out.println("client connection received");
System.out.println("sctpChannel.getRemoteAddresses() = " + sctpChannel.getRemoteAddresses());
System.out.println("sctpChannel.association() = " + sctpChannel.association());
MessageInfo messageInfo = sctpChannel.receive(rxBuffer=ByteBuffer.allocateDirect(64000) , null, null);
int len= messageInfo.bytes();
System.out.println("Server... Total bytes recived "+len);
System.out.println("Server... "+messageInfo);
rxBuffer.flip();
byte[] data = new byte[len];
rxBuffer.get(data);
rxBuffer.clear();
System.out.println("Server..... data "+Arrays.toString(data));
System.out.println("Server..... close connection");
}
}
}