Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I need to send string messages from Java program to C# program in real time.
There are many examples in the Internet but I can't find anything good for my purpose that is (probably) Java client (sockets code) and c# server (sockets code).
Thank you.
Posted
Updated 13-May-11 15:02pm
v2
Comments
Sandeep Mewara 14-May-11 1:50am    
Why not try and write your own? Looking for exact code? Thats the reason you are here for?
Chil Umez 14-May-11 12:52pm    
Please mention ur purpose so that some one can suggest.
Otherwise u get same links from everyone where you will have problem in selecting good one

For the C# part, check out TcpListener [^] and TcpClient[^] both example from MSDN are good beginner samples and should get you started.
 
Share this answer
 
v2
And lots more here[^].
 
Share this answer
 
I've found a good, working solution. Using UDP sockets:

Java code:
<code>
public void runJavaSocket() {
System.out.println("Java Sockets Program has started."); int i=0;

try {
DatagramSocket socket = new DatagramSocket();
System.out.println("Sending the udp socket...");
// Send the Message "HI"
socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
while (true)
{
System.out.println("Sending hi " + i);
Thread.currentThread();
Thread.sleep(1000);
socket.send(toDatagram("HI " + String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
public DatagramPacket toDatagram(
String s, InetAddress destIA, int destPort) {
// Deprecated in Java 1.1, but it works:
byte[] buf = new byte[s.length() + 1];
s.getBytes(0, s.length(), buf, 0);
// The correct Java 1.1 approach, but it's
// Broken (it truncates the String):
// byte[] buf = s.getBytes();
return new DatagramPacket(buf, buf.length,
destIA, destPort);
}
</code>

C# code:
<code>
string returnData;
byte[] receiveBytes;
//ConsoleKeyInfo cki = new ConsoleKeyInfo();

using (UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
{
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
while (true)
{
receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine(returnData);
}
}
<code>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900