• Java与C# socket通信


    1. 字符集

    Java与C#对于字符串的默认字符集都是Unicode,所以这里不需要自己手动统一字符编码;

    2. 数据处理

    Java字符串传值C#之后会在前后多出两个字符(2+2 = 4),这个原因暂时不清楚,可能是在传输过程中自动加的头尾吧【待续】,所以当C#接收到数据后,需要首位分别截掉两个字符;

    3. 统一字符集(可选)

    如果需要转变字符集,则可以通过以下操作统一:

    // Java
    private String convertUTFToGBK(String str) throws UnsupportedEncodingException {
            String returnStr;
            byte[] bytes = str.getBytes("gbk");// 这里输入需要的字符集名称(要求是Java支持的)
            returnStr = new String(bytes, "gbk");
            System.out.println("要发送的消息:" + returnStr+"【GBK】");
            return str;
        }
    
    // C#
    private string ConvertToGBK(byte[] data)
            {
                string returnStr;
                Encoding encoding = Encoding.GetEncoding("GBK");
                returnStr = encoding.GetString(data);
                return returnStr;
            }
    

    4. 源码

    // Java
    public class SimpleSocketClientTest {
        private Socket clientSocket;
        private DataInputStream inStream;// 客户端的输入流为服务器端发来的消息
        private DataOutputStream outStream;// 客户端的输出流为发向服务器的消息
    
        public static void main(String[] args) {
            new SimpleSocketClientTest();
        }
    
        public SimpleSocketClientTest() {
            clientSocket = new Socket();
            connect("127.0.0.1", 8885);
            // monitor
            new Scanner(System.in).next();
        }
    
        // 连接服务器
        public void connect(String ip, int port) {
            SocketAddress host = new InetSocketAddress(ip, port);
            try {
                clientSocket.connect(host, 1000);
                System.out.println("连接服务器(" + clientSocket.getRemoteSocketAddress() + ")成功");
                inStream = new DataInputStream(clientSocket.getInputStream());
                outStream = new DataOutputStream(clientSocket.getOutputStream());
                System.out.println("输入/输出流创建成功");
                // 发送消息
                String sendMsg = "你好";
                System.out.println("要发的消息是:" + sendMsg+"【UTF-8】");
                sendListener(sendMsg);
            } catch (Exception e) {
                System.out.println("连接异常,检查网络设置。");
            }
        }
    
        private void sendListener(String strToSend) throws Exception {
            outStream.writeUTF(strToSend);
        }
    }
    
    // C#
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    namespace ServerFirBlog
    {
        class Program
        {
            private string ipAddr = "127.0.0.1";
            private int port = 8885;
            private IPEndPoint endPoint;
            private Socket serverSocket;
            private Socket client;
            Encoding encoding;
    
            static void Main(string[] args)
            {
                new Program().Launcher();
                Console.ReadKey();
            }
    
            private void Launcher()
            {
                encoding = Encoding.GetEncoding("GBK");
                endPoint = new IPEndPoint(IPAddress.Parse(ipAddr), port);
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(endPoint);
                serverSocket.Listen(0);
                AsyncAccept(serverSocket);
            }
    
            /// <summary>  
            /// 接收客户端连接
            /// </summary>  
            /// <param name="socket"></param>  
            private void AsyncAccept(Socket socket)
            {
                socket.BeginAccept(asyncResult =>
                {
                    //获取客户端套接字  
                    client = socket.EndAccept(asyncResult);
                    Console.WriteLine(string.Format("客户端{0}请求连接...", client.RemoteEndPoint));
                    AsyncReveive(client);
                }, null);
            }
    
            /// <summary>  
            /// 接收消息  
            /// </summary>  
            /// <param name="client"></param>  
            private void AsyncReveive(Socket socket)
            {
                byte[] data = new byte[1024];
                try
                {
                    //开始接收消息  
                    socket.BeginReceive(data, 0, data.Length, SocketFlags.None,
                    asyncResult =>
                    {
                        int length = socket.EndReceive(asyncResult);
                        string msgContent = Encoding.UTF8.GetString(data).Substring(2, length - 2);
                        Console.WriteLine(string.Format("客户端发送消息:{0}", msgContent));
                    }, null);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
    

    5. 运行结果

    不再展示(因为我懒

  • 相关阅读:
    Demystifying ASP.NET MVC 5 Error Pages and Error Logging
    分享一个异步任务在遇到IO异常时支持递归回调的辅助方法
    ENode 2.0
    CQRSES架构介绍
    工欲善其事,必先利其器
    写了一个简单的NodeJS实现的进程间通信的例子
    谈一下关于CQRS架构如何实现高性能
    h5可伸缩布局方案
    Android总结之WebView与Javascript交互[转]
    Eclipse将引用了第三方jar包的Java项目打包成jar文件的两种方法[转]
  • 原文地址:https://www.cnblogs.com/YuanShiRenY/p/JAVA_C-sharp_SocketCommmunication.html
Copyright © 2020-2023  润新知