套接字:将字符串从 Java 发送到 C#?

发布于 2024-11-07 00:27:09 字数 105 浏览 1 评论 0原文

我需要将字符串消息从 Java 程序实时发送到 C# 程序。 互联网上有很多例子,但你找不到任何适合我的目的的东西,即(可能)Java 客户端(套接字代码)和 C# 服务器(套接字代码)。 谢谢。

I need to send string messages from Java program to C# program in real time.
There are many examples in the Internet but U can't find anything good for my purpose that is (probably) Java client (sockets code) and c# server (sockets code).
Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

往昔成烟 2024-11-14 00:27:09

好吧,我已经在我的一个项目中做到了这一点,所以这里是:
免责声明:一些代码(实际上只有一点点)是基于nakov聊天服务器的。
另请注意,我对以 UTF-8 发送和接收的所有消息进行解码和编码。

Java 代码:

Class: Server

import java.net.*;
import java.io.*;
import javax.swing.*; 

public class Server
{

    private static void createAndShowGUI() {
        //Create and set up the window
    }


public static final int LISTENING_PORT = 2002; 

public static void main(String[] args)
{
    // Open server socket for listening
    ServerSocket serverSocket = null;
    try 
    {
       serverSocket = new ServerSocket(LISTENING_PORT);
       javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               createAndShowGUI();
           }
       });
       //System.out.println("Server started on port " + LISTENING_PORT);
    }
    catch (IOException se) 
    {
       System.err.println("Can not start listening on port " + LISTENING_PORT);
       se.printStackTrace();
       System.exit(-1);
    }

    // Start ServerDispatcher thread
    ServerDispatcher serverDispatcher = new ServerDispatcher();


    // Accept and handle client connections
    while (true) 
    {   
       try  
       {
           Socket socket = serverSocket.accept();
           ClientInfo clientInfo = new ClientInfo();
           clientInfo.mSocket = socket;
           ClientListener clientListener =
               new ClientListener(clientInfo, serverDispatcher);
           ClientSender clientSender =
               new ClientSender(clientInfo, serverDispatcher);
           clientInfo.mClientListener = clientListener;
           clientInfo.mClientSender = clientSender;
           clientListener.start();
           clientSender.start();
           serverDispatcher.addClient(clientInfo);
       }
       catch (IOException ioe) 
       {
           ioe.printStackTrace();
       }
    }
}

}

Class Message Dispatcher:

    import java.io.UnsupportedEncodingException;
        import java.net.*;
    import java.util.*;

    public class ServerDispatcher 
        {
        private Vector mMessageQueue = new Vector();
        private Vector<ClientInfo> mClients = new Vector<ClientInfo>();


    public synchronized void addClient(ClientInfo aClientInfo) {
        mClients.add(aClientInfo);
    }

    public synchronized void deleteClient(ClientInfo aClientInfo) {
        int clientIndex = mClients.indexOf(aClientInfo);
        if (clientIndex != -1)
            mClients.removeElementAt(clientIndex);
    }


    private synchronized void sendMessageToAllClients(String aMessage)
    {
        for (int i = 0; i < mClients.size(); i++) {
            ClientInfo infy = (ClientInfo) mClients.get(i);
            infy.mClientSender.sendMessage(aMessage);
                              } 
    }   




    public void sendMessage(ClientInfo aClientInfo, String aMessage) {
        aClientInfo.mClientSender.sendMessage(aMessage);

    }


}

Class: ClientInfo

/**
 *
 * ClientInfo class contains information about a client, connected to the server.
 */

import java.awt.List;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;

public class ClientInfo
{

    public int userID=-1;
    public Socket mSocket = null;
    public ClientListener mClientListener = null;
    public ClientSender mClientSender = null;
}

Class ClientListner:

/**
 * ClientListener class is purposed to listen for client messages and
 * to forward them to ServerDispatcher.
 */

import java.io.*;
import java.net.*;

public class ClientListener extends Thread {
    private ServerDispatcher mServerDispatcher;
    private ClientInfo mClientInfo;
    private BufferedReader mIn;
    private String message;
    private String decoded = null;

    public ClientListener(ClientInfo aClientInfo,
            ServerDispatcher aServerDispatcher) throws IOException {
        mClientInfo = aClientInfo;
        mServerDispatcher = aServerDispatcher;
        Socket socket = aClientInfo.mSocket;
        mIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    /**
     * Until interrupted, reads messages from the client socket, forwards them
     * to the server dispatcher and notifies the server dispatcher.
     */
    public void run() {
        message = "";
        while (!isInterrupted()) {
            try {
                message = mIn.readLine();
                if (message == null)
                    break;
                try {
                    decoded = URLDecoder.decode(message, "UTF-8");
                } catch (UnsupportedEncodingException e)
                    e.printStackTrace();
                }
                mServerDispatcher.sendMessage(mClientInfo, decoded);

            } 

            catch (IOException e) {
                break;
            }

        }

        // Communication is broken. Interrupt both listener and sender threads
        mClientInfo.mClientSender.interrupt();
        mServerDispatcher.deleteClient(mClientInfo);
    }

}

Class:ClientSender

/**
 * Sends messages to the client. Messages are stored in a message queue. When
 * the queue is empty, ClientSender falls in sleep until a new message is
 * arrived in the queue. When the queue is not empty, ClientSender sends the
 * messages from the queue to the client socket.
 */

import java.io.*;
import java.net.*;
import java.util.*;

public class ClientSender extends Thread
{
    private Vector mMessageQueue = new Vector();

    private ServerDispatcher mServerDispatcher;
    private ClientInfo mClientInfo;
    private PrintWriter mOut;

    public ClientSender(ClientInfo aClientInfo, ServerDispatcher aServerDispatcher)
    throws IOException
    {
        mClientInfo = aClientInfo;
        mServerDispatcher = aServerDispatcher;
        Socket socket = aClientInfo.mSocket;
        mOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    /**
     * Adds given message to the message queue and notifies this thread
     * (actually getNextMessageFromQueue method) that a message is arrived.
     * sendMessage is called by other threads (ServeDispatcher).
     */
    public synchronized void sendMessage(String aMessage)
    {
        mMessageQueue.add(aMessage);
        notify();
    }

    /**
     * @return and deletes the next message from the message queue. If the queue
     * is empty, falls in sleep until notified for message arrival by sendMessage
     * method.
     */
    private synchronized String getNextMessageFromQueue() throws InterruptedException
    {
        while (mMessageQueue.size()==0)
           wait();
        String message = (String) mMessageQueue.get(0);
        mMessageQueue.removeElementAt(0);
        return message;
    }

    /**
     * Sends given message to the client's socket.
     */
    private void sendMessageToClient(String aMessage)
    {
         String encoded;
        try {
            encoded = URLEncoder.encode(aMessage,"UTF-8");
            mOut.println(encoded);
            mOut.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * Until interrupted, reads messages from the message queue
     * and sends them to the client's socket.
     */
    public void run()
    {
        try {
           while (!isInterrupted()) {
               String message = getNextMessageFromQueue();


               sendMessageToClient(message);
           }
        } catch (Exception e) {
           // Commuication problem
       break;
        }

        // Communication is broken. Interrupt both listener and sender threads
        mClientInfo.mClientListener.interrupt();
        mServerDispatcher.deleteClient(mClientInfo);
    }

}

好的是java代码,现在是c#代码

c#代码:

使用的变量:

    private StreamWriter swSender;
    private StreamReader srReceiver;
    private TcpClient tcpServer;
    private Thread thrMessaging;
    private IPAddress ipAddr;
    private bool Connected;

函数:Intelize连接:

private void InitializeConnection()
{
    // Parse the IP address

    string ipAdress = "XXX.XXX.XXX.XXX";
    ipAddr = IPAddress.Parse(ipAdress);


    // Start a new TCP connections to the chat server
    tcpServer = new TcpClient();
    try
    {
        tcpServer.Connect(ipAddr, 2002);
        swSender = new StreamWriter(tcpServer.GetStream());


        // Start the thread for receiving messages and further communication
        thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
        thrMessaging.Start();
        Connected=true;
    }
        catch (Exception e2)
        {
            MessageBox.Show(e2.ToString());
        }
    }



}

函数:ReciveMessages

private void ReceiveMessages()
        {
            // Receive the response from the server
            srReceiver = new StreamReader(tcpServer.GetStream());
            while (Connected)
            {
                String con = srReceiver.ReadLine();
                string StringMessage = HttpUtility.UrlDecode(con, System.Text.Encoding.UTF8);

                processMessage(StringMessage);



            }
        }

函数: proceesMessage:

private void processMessage(String p)
        {
        // do something with the message
        }

函数sendMessage:

 private void SendMessage(String p)
        {
            if (p != "")
            {
                p = HttpUtility.UrlEncode(p, System.Text.Encoding.UTF8);
                swSender.WriteLine(p);
                swSender.Flush();

            }

        }

这就是java服务器和c#客户端之间进行通信所需的全部内容。如果您有任何疑问,请随时在此发布。

Ok i already did this in one of my projects so here it is:
disclaimer: some of the code (only a little bit actually) is based on nakov chat server.
also note that i decode and encode all the messages sent and recived in UTF-8.

Java Code:

Class: Server

import java.net.*;
import java.io.*;
import javax.swing.*; 

public class Server
{

    private static void createAndShowGUI() {
        //Create and set up the window
    }


public static final int LISTENING_PORT = 2002; 

public static void main(String[] args)
{
    // Open server socket for listening
    ServerSocket serverSocket = null;
    try 
    {
       serverSocket = new ServerSocket(LISTENING_PORT);
       javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               createAndShowGUI();
           }
       });
       //System.out.println("Server started on port " + LISTENING_PORT);
    }
    catch (IOException se) 
    {
       System.err.println("Can not start listening on port " + LISTENING_PORT);
       se.printStackTrace();
       System.exit(-1);
    }

    // Start ServerDispatcher thread
    ServerDispatcher serverDispatcher = new ServerDispatcher();


    // Accept and handle client connections
    while (true) 
    {   
       try  
       {
           Socket socket = serverSocket.accept();
           ClientInfo clientInfo = new ClientInfo();
           clientInfo.mSocket = socket;
           ClientListener clientListener =
               new ClientListener(clientInfo, serverDispatcher);
           ClientSender clientSender =
               new ClientSender(clientInfo, serverDispatcher);
           clientInfo.mClientListener = clientListener;
           clientInfo.mClientSender = clientSender;
           clientListener.start();
           clientSender.start();
           serverDispatcher.addClient(clientInfo);
       }
       catch (IOException ioe) 
       {
           ioe.printStackTrace();
       }
    }
}

}

Class Message Dispatcher:

    import java.io.UnsupportedEncodingException;
        import java.net.*;
    import java.util.*;

    public class ServerDispatcher 
        {
        private Vector mMessageQueue = new Vector();
        private Vector<ClientInfo> mClients = new Vector<ClientInfo>();


    public synchronized void addClient(ClientInfo aClientInfo) {
        mClients.add(aClientInfo);
    }

    public synchronized void deleteClient(ClientInfo aClientInfo) {
        int clientIndex = mClients.indexOf(aClientInfo);
        if (clientIndex != -1)
            mClients.removeElementAt(clientIndex);
    }


    private synchronized void sendMessageToAllClients(String aMessage)
    {
        for (int i = 0; i < mClients.size(); i++) {
            ClientInfo infy = (ClientInfo) mClients.get(i);
            infy.mClientSender.sendMessage(aMessage);
                              } 
    }   




    public void sendMessage(ClientInfo aClientInfo, String aMessage) {
        aClientInfo.mClientSender.sendMessage(aMessage);

    }


}

Class: ClientInfo

/**
 *
 * ClientInfo class contains information about a client, connected to the server.
 */

import java.awt.List;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;

public class ClientInfo
{

    public int userID=-1;
    public Socket mSocket = null;
    public ClientListener mClientListener = null;
    public ClientSender mClientSender = null;
}

Class ClientListner:

/**
 * ClientListener class is purposed to listen for client messages and
 * to forward them to ServerDispatcher.
 */

import java.io.*;
import java.net.*;

public class ClientListener extends Thread {
    private ServerDispatcher mServerDispatcher;
    private ClientInfo mClientInfo;
    private BufferedReader mIn;
    private String message;
    private String decoded = null;

    public ClientListener(ClientInfo aClientInfo,
            ServerDispatcher aServerDispatcher) throws IOException {
        mClientInfo = aClientInfo;
        mServerDispatcher = aServerDispatcher;
        Socket socket = aClientInfo.mSocket;
        mIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    /**
     * Until interrupted, reads messages from the client socket, forwards them
     * to the server dispatcher and notifies the server dispatcher.
     */
    public void run() {
        message = "";
        while (!isInterrupted()) {
            try {
                message = mIn.readLine();
                if (message == null)
                    break;
                try {
                    decoded = URLDecoder.decode(message, "UTF-8");
                } catch (UnsupportedEncodingException e)
                    e.printStackTrace();
                }
                mServerDispatcher.sendMessage(mClientInfo, decoded);

            } 

            catch (IOException e) {
                break;
            }

        }

        // Communication is broken. Interrupt both listener and sender threads
        mClientInfo.mClientSender.interrupt();
        mServerDispatcher.deleteClient(mClientInfo);
    }

}

Class:ClientSender

/**
 * Sends messages to the client. Messages are stored in a message queue. When
 * the queue is empty, ClientSender falls in sleep until a new message is
 * arrived in the queue. When the queue is not empty, ClientSender sends the
 * messages from the queue to the client socket.
 */

import java.io.*;
import java.net.*;
import java.util.*;

public class ClientSender extends Thread
{
    private Vector mMessageQueue = new Vector();

    private ServerDispatcher mServerDispatcher;
    private ClientInfo mClientInfo;
    private PrintWriter mOut;

    public ClientSender(ClientInfo aClientInfo, ServerDispatcher aServerDispatcher)
    throws IOException
    {
        mClientInfo = aClientInfo;
        mServerDispatcher = aServerDispatcher;
        Socket socket = aClientInfo.mSocket;
        mOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    /**
     * Adds given message to the message queue and notifies this thread
     * (actually getNextMessageFromQueue method) that a message is arrived.
     * sendMessage is called by other threads (ServeDispatcher).
     */
    public synchronized void sendMessage(String aMessage)
    {
        mMessageQueue.add(aMessage);
        notify();
    }

    /**
     * @return and deletes the next message from the message queue. If the queue
     * is empty, falls in sleep until notified for message arrival by sendMessage
     * method.
     */
    private synchronized String getNextMessageFromQueue() throws InterruptedException
    {
        while (mMessageQueue.size()==0)
           wait();
        String message = (String) mMessageQueue.get(0);
        mMessageQueue.removeElementAt(0);
        return message;
    }

    /**
     * Sends given message to the client's socket.
     */
    private void sendMessageToClient(String aMessage)
    {
         String encoded;
        try {
            encoded = URLEncoder.encode(aMessage,"UTF-8");
            mOut.println(encoded);
            mOut.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * Until interrupted, reads messages from the message queue
     * and sends them to the client's socket.
     */
    public void run()
    {
        try {
           while (!isInterrupted()) {
               String message = getNextMessageFromQueue();


               sendMessageToClient(message);
           }
        } catch (Exception e) {
           // Commuication problem
       break;
        }

        // Communication is broken. Interrupt both listener and sender threads
        mClientInfo.mClientListener.interrupt();
        mServerDispatcher.deleteClient(mClientInfo);
    }

}

Ok this is the java code,now to the c# code

c# Code:

Varibales used:

    private StreamWriter swSender;
    private StreamReader srReceiver;
    private TcpClient tcpServer;
    private Thread thrMessaging;
    private IPAddress ipAddr;
    private bool Connected;

Function: Intelize connection:

private void InitializeConnection()
{
    // Parse the IP address

    string ipAdress = "XXX.XXX.XXX.XXX";
    ipAddr = IPAddress.Parse(ipAdress);


    // Start a new TCP connections to the chat server
    tcpServer = new TcpClient();
    try
    {
        tcpServer.Connect(ipAddr, 2002);
        swSender = new StreamWriter(tcpServer.GetStream());


        // Start the thread for receiving messages and further communication
        thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
        thrMessaging.Start();
        Connected=true;
    }
        catch (Exception e2)
        {
            MessageBox.Show(e2.ToString());
        }
    }



}

Function: ReciveMessages

private void ReceiveMessages()
        {
            // Receive the response from the server
            srReceiver = new StreamReader(tcpServer.GetStream());
            while (Connected)
            {
                String con = srReceiver.ReadLine();
                string StringMessage = HttpUtility.UrlDecode(con, System.Text.Encoding.UTF8);

                processMessage(StringMessage);



            }
        }

Function: proceesMessage:

private void processMessage(String p)
        {
        // do something with the message
        }

Function sendMessage:

 private void SendMessage(String p)
        {
            if (p != "")
            {
                p = HttpUtility.UrlEncode(p, System.Text.Encoding.UTF8);
                swSender.WriteLine(p);
                swSender.Flush();

            }

        }

thats it thats all you need to have communication between java server and c# client. if you have any questions dont hesitate to post them here.

友谊不毕业 2024-11-14 00:27:09
  1. 选择用于编码/发送字符串的协议。例如:

    <字符串长度(4 字节)><字符串数据(长度字节)>

  2. 编写一些 Java 代码来发送遵循您在 # 中选择的任何协议的字符串1.因此,使用上面的示例,您可以执行以下操作:

    public static void writeString(String string, OutputStream out) throws IOEXception {
        if (string == null || "".equals(string)) {
            //无事可做
            返回;
        }
        int 长度 = string.length();
    
        //同步,以便两个线程不会尝试同时写入同一个流
        同步(输出){
            out.write((长度>>24)&0xFF);
            out.write((长度>>16)&0xFF);
            out.write((长度>>8)&0xFF);
            out.write(长度&0xFF);
            out.write(string.getBytes());
            出.flush();
        }
    }
    
  3. 用 C# 编写一些等效代码来解码正在发送的字符串。它看起来很像您的 Java 代码,只不过是读取而不是写入。

  1. Choose a protocol for encoding/sending your strings. For instance:

    <length of string (4 bytes)><string data (length bytes)>

  2. Write some Java code to send a string that follows whatever protocol you chose in #1. So using the example above, you could do something like:

    public static void writeString(String string, OutputStream out) throws IOEXception {
        if (string == null || "".equals(string)) {
            //nothing to do
            return;
        }
        int length = string.length();
    
        //synchronize so that two threads don't try to write to the same stream at the same time
        synchronized(out) {
            out.write((length >> 24) & 0xFF);
            out.write((length >> 16) & 0xFF);
            out.write((length >> 8) & 0xFF);
            out.write(length & 0xFF);
            out.write(string.getBytes());
            out.flush();
        }
    }
    
  3. Write some equivalent code in C# to decode the strings that are being sent. It will look a lot like your Java code, except with reads instead of writes.

絕版丫頭 2024-11-14 00:27:09

我想我已经找到了一个好的、可行的解决方案。使用 UDP 套接字:

Java 代码

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);
}

C# 代码

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);
    }
}

I think I've found a good, working solution. Using UDP sockets:

Java 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);
}

C# 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);
    }
}
错爱 2024-11-14 00:27:09

我只想使用 SOAP 协议。您可以在 C# 端使用 WCF,在 Java 端使用 JMS(Java 消息传递)。这两种技术都是基于 SOAP 构建的,因此它们可以读取彼此的消息。他们都使用 WSDL。

I would just use SOAP protocol. You can use WCF on the C# side and JMS (Java messging) on the Java side. Both these technologies are built on SOAP so they can read each other's messages. They both use WSDL.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文