I'm using sockets to communicate between C# and Java. However, My stream in C# keeps freezing whenever I try to read from it. I'm wondering if someone might be able to help me out.
Java Code -
public void Send(String message) throws Exception {
sock = new Socket("127.0.0.1", 2913);
PrintStream PS = new PrintStream(sock.getOutputStream());
PS.println(message);
}
C# Code -
private static void Listen(){
serverSocket.Start ();
while (true) {
TcpClient Client = serverSocket.AcceptTcpClient ();
NetworkStream stream = Client.GetStream ();
byte[] read = new byte[10025];
stream.Read (read, 0, (int)Client.ReceiveBufferSize);
Client.GetStream().Flush();
string dataFromClient = System.Text.Encoding.ASCII.GetString (read);
//Output data from client
Client.Close();
}
}
I've managed to ensure that the client is connecting, and that all of the C# code is executing up to the point where it calls
stream.Read();
I'm wondering if someone might know why it is halting on stream.Read();. Is my java trying to send the message before C# has a chance to listen to it? If so, how would I fix that. I've tried using
while(!sock.isConnected()) Thread.sleep(1);
in my Java, but it didn't help.
I ended up fixing it by using this for my C# function.
private static void Listen(){
serverSocket.Start ();
while (true) {
TcpClient Client = serverSocket.AcceptTcpClient ();
StreamReader sr = new StreamReader(Client.GetStream ());
string dataFromClient = sr.ReadLine();
//Output Data From Client
Client.Close();
}
}
I guess using the stream reader instead of trying to read the bytes myself fixed it.
Related
I am working on a Java-C# socket communication and I would like to send the coordinates of a C# object to java periodically. The problem is that the java client Stream only reads the coordinates (20 mile long buffer) when I close the connection. I would like the connection to remain open and the coordinates to update without having to open and close this connection all the time.
P.S. This was working but I somehow deleted the previous C# script I was using now I cannot figure it out.
The Java LocationRequester, will connect to the server and then periodically call getline() and pass it to coordinates. The connect part works and getline() only completes if I close the connection, otherwise it hangs. When I close the connection I get a super long row of coordinates.
public Socket clientSocket;
BufferedReader inputBuff;
String hostName;
int hostPort;
public LocationListener(String host, int port) {
hostName = host;
hostPort = port;
}
public void connect()
{
try {
clientSocket = new Socket(hostName, hostPort);
System.out.println("Connected to"+clientSocket.toString());
InputStream input = clientSocket.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
inputBuff = new BufferedReader(reader);
String str;
}
catch(IOException e)
{
e.printStackTrace();
}
}
public String getLine() {
String rstring = "";
try {
rstring = inputBuff.readLine();
System.out.println(rstring);
}
catch(IOException e) {
e.printStackTrace();
}
return rstring;
}
C# code seems to be where the problem is.
private void Start()
{
IPAddress address = IPAddress.Any;
server = new TcpListener(address, 9999);
server.Start();
client = server.AcceptTcpClient();
StartCoroutine(SendCords());
}
private IEnumerator SendCords()
{
while (true)
{
yield return new WaitForSeconds(0.5f);
NetworkStream stream = client.GetStream();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(transform.position.ToString());
stream.Write(msg, 0, msg.Length);
stream.Flush();
// client.Close();
Debug.Log("Sending "+transform.position);
}
}
The java code is reading a line. That means it will block until it gets a line feed character '\n'. And I guess your C# code is not adding a line feed. In my opinion, if you add a line feed character in the end, to your C# message payload, the java code should get the information and come out of the wait. Give a try.
#ferosekhanj has already said very well. I add that the function ofBufferedReader.readLine() will stop reading at'\n' and also at EOF. This is why when your C# program close the Socket, and your java program will receive a super long row of coordinates.
I am trying to send data to one of my servers and receive an ACK back from it. However, the processing gets hung up when waiting for a response from the server. I know for a fact that there is a connection because I can see the data reaching the server. I also know that the server is outputting data correctly because my C# client is receiving data back from the server. I will note that this client is running on a centOS virtual machine. The server is a remote windows machine. I wouldn't imagine that there would be an issue due to the virtual environment because I am able to use an SNMP java client (SNMP4j package) to make calls to a remote server. I believe my server is outputting raw binary too, but I would expect to see some kind of output either way.
// A Java program for a Client
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
private DataInputStream serveroutput= null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
serveroutput = new DataInputStream(socket.getInputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
System.out.println(serveroutput.readLine())
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
Could be great if you would share the otherside codes. (sorry cannot comment yet)
Try use something else over writeUTF(), simply maybe a PrintStream, as mentioned by #marquis-of-lorne (read|write)UTF may be confusing by the peer.
Also this might be a good practice to flush() out the output from both side when there is nothing else to send to make sure data is sent completely.
You may also try BufferedReader over InputDataStream as you are trying to read lines. readLine() from InputDataStream is deprecated.
I have C# program that makes a tcp connection with another c# program. In the c# program to send an message I did this :
private TcpClient client;
private void SendPulse()
{
byte[] send_Buffer;
port = 11000;
while (true)
{
lock (locked)
{
try
{
BlockID = 1003;
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter w = new BinaryWriter(ms))
{
NetworkStream stream = client.GetStream();
BlockID = 1003;
LengthMessage = 84;
// Header :
w.Write(BeginMessage);
w.Write(BlockID);
w.Write(LengthMessage);
w.Write(RadarID);
w.Write(Time);
w.Write(ModeSystem);
w.Write(Icd_primary_var);
w.Write(Icd_secondary_ver);
// Data :
w.Write(StatusSystem);
send_Buffer = ms.ToArray();
stream.Write(send_Buffer, 0, send_Buffer.Length);
Thread.Sleep(3000); // Send pulse every 3 seconds.
}
}
}
catch
{
}
}
}
}
The idea is to write in binarywriter and than convert the memory we wrote on to byte array and to send it.
Now I have Java programming. I want to do it too, I have connection with C# but I dont know how to send it. I did DataOutputStream but it send every parameter alone, I want all in 1 array of bytes exactly like in the c# code.
Thanks for helpers.
If you want to use DataOutputStream, you can wrap it around a BufferedOutputStream and flush() it when you are done.
Or you can use an NIO ByteBuffer and write it to the socket.
To make the message easier to decode I would add the length to the start, unless you know it every message will be that length.
I need to receive an array or a class containing floats from a c++ client to java server using sockets. But the InputStreamReader is not getting it right. Any reasons.
Any suggestions for simpler ways would be appreciated.
Thanks.
Java Server Code
public static void main(String[] args) throws IOException {
// TODO code application logic here
Values values=new Values();
gui display=new gui();
display.setVisible(true);
ServerSocket Sock=new ServerSocket(9090);
try{
while(true){
System.out.println("Waiting");
Socket socket=Sock.accept();
System.out.println("Connected..");
InputStream ins=socket.getInputStream();
InputStreamReader insr= new InputStreamReader(ins);
BufferedReader br=new BufferedReader(insr);
byte[]Array=br.readLine().getBytes("UTF-8");
// values.SetValues(Array);
values.tWidth=Array[0];
values.waterLevel=Array[4];
values.camHeight=Array[8];
values.camViewAngleY=Array[12];
values.camViewAngleX=Array[16];
values.distFromCamBank=Array[20];
values.distTwoPoints=Array[24];
values.AvgVelocity=Array[28];
values.crossSecArea=Array[32];
values.Flow=Array[36];
values.camTiltAngle=Array[40];
values.aboveWater=Array[44];
System.out.println(values.tWidth);
System.out.println(values.waterLevel);
display.SetValues(values);
socket.close();
}
}
finally{
Sock.close();
}
}
}
I am storing those float in a Class called Values. But the values I get are junk. I am checking the values in C++ code before sending and they seem fine. Dont know where its going wrong.
Please Help...!!
I suggest you try
DataInputStream ins = new DataInputStream(socket.getInputStream());
byte[] bytes = new bytes[48];
ins.readFuly(bytes);
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());
values.tWidth = bb.getFloat();
value.waterLevel = bb.getFloat();
// etc
i want to know how to send data using the AMF format from my flex AIR project to a socket written in Java. I am getting CorruptedStreamException when sending data using writeUTFBytes() methods. Has anyone experienced similar problems? Also can AMF be used only if i am using LCDS only?
private SimpleServer(int port)
{
System.out.println(">> Starting SimpleServer on port " + port);
try
{
socket = new ServerSocket(port);
incoming = socket.accept();
objectInputStream = new ObjectInputStream(incoming.getInputStream());
objectOutputStream = new ObjectOutputStream(incoming.getOutputStream());
boolean done = false;
while (!done)
{
Object obj = objectInputStream.readObject();
System.out.println( obj.toString() );
if(obj == null)
{
done = true;
incoming.close();
}
}
}
catch (Exception e)
{
System.out.println(e);
}
}
And my as3 function to send data to the server is
private function onSendClick():void
{
var host:String = "10.87.118.8";
var port:int = 9090;
var socket:Socket = new Socket();
trace("Connect");
socket.connect(host, port);
trace("write");
socket.writeUTFBytes("HelloSocket");
trace("flush");
socket.flush();
}
AMF stands for Action Message Format.
It is a specification which defines how to transfer data between an ActionScript client and external system.
Therefore, many server side technologies incorporate AMF into their packages.
For example BlazeDS, GraniteDS, pyAMF, amfphp, ...
Hence, to answer your question, no AMF can also be used outside of LCDS.
It is merely an "envelope" you can use to send your message (=data) in.
It should even work with sockets.
I believe there is an open source library called merapi that uses this principle.
Cheers
This is an old question now, but since, on the ActionScript side you are using
socket.writeUTFBytes("HelloSocket");
On the Java side, change it to this and it will work without AMF :
BufferedReader in = new BufferedReader (new InputStreamReader((clientSocket.getInputStream())));
String line = "";
while( (line = in.readLine()) != null) {
processMessage(line);
}