C#客户端与Java服务端通过socket通信

工作环境需求:服务端使用C#编写,客户端使用Java编写。以下是一个C#客户端与Java服务端通过socket通信的一个Demo。

  • Java服务端代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;

    public Server() {
        try {
            //设置你服务器监听的端口为10000,用户能使用的端口为1025-65535
            serverSocket = new ServerSocket(2000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建新的监听主线程,这个线程创建ServerSocket监听
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    Socket socket = null;
                    try {
                        socket = serverSocket.accept();
                        //当监听到了客户端连接后,创建新线程传输数据,这样可以实现多个客户端同时访问
                        new Thread(new SocketHandler(socket)).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    class SocketHandler implements Runnable {
        private Socket socket;
        private BufferedReader reader;
        private PrintWriter writer;

        SocketHandler(Socket socket) {
            try {
                this.socket = socket;
                reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), "GB2312"));
                writer = new PrintWriter(socket.getOutputStream(), true);
                int i = 0;
                while (true) {
                    i++;
                    writer.println("-------welcome---------" + i );
                    Thread.sleep(3000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //这里是覆盖实现接口Runnable里的run()
        public void run() {
            try {
                //读取数据,这里只能读取一行String
                String line = reader.readLine();
                System.out.println(line);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //最后要关闭Socket
                try {
                    if (socket != null) socket.close();
                    if (reader != null) reader.close();
                    if (writer != null) writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Server();
    }
}
  • C#客户端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int port = 2000;
                string host = "127.0.0.1";
                ///创建终结点EndPoint  
                IPAddress ip = IPAddress.Parse(host);
                //IPAddress ipp = new IPAddress("127.0.0.1");  
                IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndpoint实例  

                ///创建socket并连接到服务器  
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket  
                Console.WriteLine("Conneting…");
                c.Connect(ipe);//连接到服务器  

                ///向服务器发送信息  
                string sendStr = "hello!This is a socket test";
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字符串编码为字节  
                Console.WriteLine("Send Message");
                c.Send(bs, bs.Length, 0);//发送信息  

                while(true) {
                    ///接受从服务器返回的信息  
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息  
                    recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                    Console.WriteLine("client get message:{0}", recvStr);//显示服务器返回信息
                }
                /////接受从服务器返回的信息  
                //string recvStr = "";
                //byte[] recvBytes = new byte[1024];
                //int bytes;
                //bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息  
                //recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                //Console.WriteLine("client get message:{0}", recvStr);//显示服务器返回信息  
                ///一定记着用完socket后要关闭  
                c.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("argumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException:{0}", e);
            }
            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();
        }
    }
}

你可能感兴趣的:(C#客户端与Java服务端通过socket通信)