Java与C#基于Socket通信
发布日期:2022-03-09 12:36:21 浏览次数:85 分类:技术文章

本文共 6175 字,大约阅读时间需要 20 分钟。

    由于Java在网络方便的巨大影响力,以及微软推出的Framework .net平台的应用不断扩大,使得Java与C#的网络通信变得愈来愈重要。本文主要介绍java与c#的Socket通信。Java的Socket通信模块由于封装的比较高级,用起来也比较舒服。但是C#虽然有TcpClient等类库的支持,但是要与java实现底层的socket通信任然比较麻烦。本文基于C#的Socket模块与Java的Socke模块t实现底层二进制数据的通信。

一.Java作为服务器:以下是核心代码:

package com.ffg;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;public class MyServer {	public static void main(String args[])	{		try		{			ServerSocket ss=new ServerSocket(9999);			System.out.println("Listening on 9999......");			while(true)			{				try				{					Socket sc=ss.accept();					System.out.println("Request come ...");					DataInputStream din=new DataInputStream(sc.getInputStream());					DataOutputStream dout=new DataOutputStream(sc.getOutputStream());					String s=readStr(din);					System.out.println("Rec:"+s);					writeStr(dout," Hi C#,I‘m Java Sever。"+s);					dout.close();					din.close();					sc.close();				}				catch(Exception e)				{					e.printStackTrace();				}			}		}		catch(Exception e)		{			e.printStackTrace();		}	}			public static String readStr(DataInputStream din) throws IOException	{		String res=null;;		byte str[] = null;		ByteArrayOutputStream out= new ByteArrayOutputStream(1024); 		try {			byte[] temp = new byte[1024]; 			int size = 0; 			try {//循环接受数据				int temRev =0;				byte[] ba=new byte[4];				din.read(ba);				int len=byte2Int(ba);				System.out.println("len:"+len);				while ((size = din.read(temp)) != -1)				{ 						temRev+=size;					out.write(temp, 0, size);					if(temRev>=len)					{						break;					}				}			} catch (IOException e) {				e.printStackTrace();			}			str = out.toByteArray();			res = new String(str, "utf-8");		} catch (Exception e) {			e.printStackTrace();		}finally{			try {out.close();} catch (IOException e) {e.printStackTrace();}		}		return res;	}	public static void writeStr(DataOutputStream dout,String str) throws IOException	{		PrintStream ps= new PrintStream(dout, true);		ps.println(str);// 将数据写入到SOCKET中,返回客户端。		dout.flush();		ps.close();	}	@SuppressWarnings("unused")	private static byte[] int2Byte(int intValue) {		byte[] b = new byte[4];		for (int i = 0; i < 4; i++) {			b[i] = (byte) (intValue >> 8 * (3 - i) & 0xFF);		}		return b;	}	private static int byte2Int(byte[] b) {		int intValue = 0;		for (int i = 0; i < b.length; i++) {			intValue += (b[i] & 0xFF) << (8 * (3 - i));		}		return intValue;	}}

二.C#作为客户端,向服务器发起连接:以下是核心代码:

using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net;using System.Diagnostics;using System.IO;namespace ffg{    class SocketUtil    {        private static readonly string SERVER_IP = "127.0.0.1";        private static readonly int SERVER_PORT = "9999";        private static Socket getConnection()        {            try            {                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(SERVER_IP), SERVER_PORT);//服务器的IP和端口                socket.Connect(ipep);                return socket;            }            catch (Exception e)            {                Debug.WriteLine(e.StackTrace);                return null;            }        }        public static String sendAndGetMsg(String str)        {            Socket sockect = getConnection();            if (sockect == null) return "error sockect is null";            try            {                 byte[] msgStr = Encoding.UTF8.GetBytes(str);             // byte[] length = BitConverter.GetBytes(msgStr.Length);                byte[] length = int2Byte(msgStr.Length);                Debug.WriteLine("msgStr.Length:" + msgStr.Length);                int lenSent = sockect.Send(length);                int bytesSent = sockect.Send(msgStr);                byte[] buffbytes = new byte[2048];                int bytesRec = sockect.Receive(buffbytes);                string res =Encoding.ASCII.GetString(buffbytes, 0, bytesRec);                sockect.Shutdown(SocketShutdown.Both);                sockect.Close();                return res;            }            catch (SocketException e)            {                Debug.WriteLine(e.StackTrace);                return "error";            }        }        public static String sendBytesAndGetMsg(String str,byte[]data)        {            Socket sockect = getConnection();            if (sockect == null) return "error sockect is null";            try            {                byte[] msgStr = Encoding.UTF8.GetBytes(str);                byte[] length = int2Byte(msgStr.Length);                Debug.WriteLine("msgStr.Length:" + msgStr.Length);                int lenSent = sockect.Send(length);                int bytesSent = sockect.Send(msgStr);                byte[] lengthData = int2Byte(data.Length);                int lenSentData = sockect.Send(lengthData);                int bytesSentData = sockect.Send(data);                byte[] buffbytes = new byte[2048];                int bytesRec = sockect.Receive(buffbytes);                string res = Encoding.ASCII.GetString(buffbytes, 0, bytesRec);                sockect.Shutdown(SocketShutdown.Both);                sockect.Close();                return res;            }            catch (SocketException e)            {                Debug.WriteLine(e.StackTrace);                return "error";            }        }        private static int byte2Int(byte[] b)        {            int intValue = 0;            for (int i = 0; i < b.Length; i++)            {                intValue += (b[i] & 0xFF) << (8 * (3 - i));            }            return intValue;        }        private static byte[] int2Byte(int intValue)        {            byte[] b = new byte[4];            for (int i = 0; i < 4; i++)            {                b[i] = (byte)(intValue >> 8 * (3 - i) & 0xFF);            }            return b;        }    }}

        总的来说,就是先将需要发送的数据的长度发送出去,而这个长度用int型表示,而int型使用四个字节编码的,即byte[4],所以发送时先发送一个byte[4]的数据,表示接下来需要发送数据的长度,再发送实际的数据(也是一个byte[])。而java端接收到时应该知道第一次接收的是byte[4],表示长度的int,需要将其解码成int,然后在继续接收实际数据的byte[]。

转载地址:https://blog.csdn.net/fuxp790028352/article/details/8472627 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:原型笔记
下一篇:学习笔记(01):2019Python全套视频教程-pip包管理命令

发表评论

最新留言

很好
[***.229.124.182]2024年04月15日 13时59分37秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章