Java Server,C#Client。 发送数据

因此,我在将数据从C#客户端发送到Java Server时遇到问题。 连接正在进行中,但是我想在某个地方弄乱了。

这是ServerSided Code

package com.chris.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server implements Runnable { private String serverName; private boolean isRunning; private ServerSocket serverSocket; private Socket clientSocket; public Server(String name, int port) { try { this.serverName = name; this.serverSocket = new ServerSocket(port); this.isRunning = true; new Thread(this).start(); } catch (IOException e) { e.printStackTrace(); } } private BufferedReader recv; public void run() { while(isRunning) { try { clientSocket = serverSocket.accept(); System.out.println("Client Connected from " + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort()); recv = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); System.out.println("Data Recieved: " + recv.readLine()); clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } 

这是客户端代码

 lass TCPClient { private TcpClient Client; private NetworkStream Stream; private Byte[] Data; public TCPClient(string address, int port) { Client = new TcpClient(); Client.Connect(address, port); Stream = Client.GetStream(); SendData("Test Data"); while (Client.Connected) { } } public void SendData(string message) { Data = System.Text.Encoding.ASCII.GetBytes(message); Stream.Write(Data, 0, Data.Length); Console.WriteLine("Sent: {0}", message); } } 

服务器注册连接,客户端似乎认为它已经发送了数据,但我不知道客户端是不是发送了数据,还是服务器没有收到数据。 考虑到Console.Writeline只是打印出转换成字节的消息,我无法分辨。

如果你想使用JSON,请参阅这篇关于让Java发送消息将你的java类型序列化为JSON并接收C#以Deserealize为C#类型的优秀文章。

摘录于Java:

 import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import com.google.gson.Gson; public class GuyServer { public static void main(String[] args) throws IOException { Gson gson = new Gson(); ServerSocket serverSocket = new ServerSocket(16001); System.out.println("Listening on port 16001. " + "Press enter to quit " + "after the next connection."); while (System.in.available() == 0) { Socket socket = serverSocket.accept(); System.out.println("A client has connected." + " Sending a new Guy down the pipe."); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); Guy guy = Guy.getRandomGuy(); String json = gson.toJson(guy); out.print(json); out.close(); socket.close(); } System.out.println("Quitting..."); serverSocket.close(); } } 

C#结束:

 using System; using System.IO; using System.Net.Sockets; using System.Web.Script.Serialization; class GuyClient { static void Main(string[] args) { String input; using (TcpClient tcpClient = new TcpClient("localhost", 16001)) using (NetworkStream networkStream = tcpClient.GetStream()) using (StreamReader streamReader = new StreamReader(networkStream)) { input = streamReader.ReadToEnd(); } Console.WriteLine("Received data: " + input + "\n"); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); Guy bob = javaScriptSerializer .Deserialize(input) as Guy; Console.WriteLine(bob.ToString()); } } 

Java类

 import java.util.ArrayList; import java.util.List; import java.util.Random; public class Guy { private String name; public String getName() { return name; } } } 

C#Serlizable类

 using System; using System.Collections.Generic; [Serializable] class Guy { public string Name { get; set; } } 

我把它清理了一下以便更容易理解。 它不会编译,但你明白了。

Java TCP客户端:您应该分别使用DataInputStreamDataOutputStream来发送和接收数据:

 try { mOutStream = new DataOutputStream(mClientSocket.getOutputStream()); mInStream = new DataInputStream(mClientSocket.getInputStream()); } catch (Exception e) { e.printStackTrace(); } 

操作输出数据流的示例(发送出去):

 public static void WriteString(DataOutputStream os, String value) throws IOException { if (value!=null) { byte[] array = value.getBytes(CHARSET); WriteBuffer(os,array); } else { WriteInt(os,0); } } public static void WriteBuffer(DataOutputStream os, byte[] array) throws IOException { if ((array!=null) && (array.length > 0) && (array.length <= MAX_BUFFER_SIZE)) { WriteInt(os,array.length); os.write(array); //os.flush(); } else { WriteInt(os,0); } } public static void WriteInt(DataOutputStream os, int value) throws IOException { byte[] intAsBytes = ConvertIntToBytes(value); os.write(intAsBytes); //os.flush(); } 

使用输入流(接收)的示例:

 public static String ReadString(DataInputStream is) throws IOException { String ret=null; int len = ReadInt(is); if ((len == 0) || (len > MAX_BUFFER_SIZE)) { ret = ""; } else { byte[] buffer = new byte[len]; is.readFully(buffer, 0, len); ret = new String(buffer, CHARSET); } return (ret); } public static int ReadInt(DataInputStream is) throws IOException { int ret=0; byte[] intAsBytes = new byte[4]; // this will just block forever... is.readFully(intAsBytes); ret = ConvertBytesToInt(intAsBytes); return (ret); } public static int ConvertBytesToInt( byte[] array) { int rv = 0; for ( int x = 3; x >= 0; x-- ) { long bv = array[ x ]; if ( x < 3 & bv < 0 ) // keeping the sign intact??? bv +=256; //rv *= 256; rv = rv << 8; rv += bv; } return rv; } 

C#TCP Client 🙁这更新了第一个答案),注意到在C#中使用BinaryWriter类似于Java中的DataOutputStream

在代码中的某处定义MAX_BUFFER_SIZE=1024 (example) const!

 public static void WriteString(BinaryWriter os, string value) { if (value!=null) { byte[] array = System.Text.Encoding.Unicode.GetBytes(value); WriteBuffer(os,array); } else { WriteInt(os,0); } } public static void WriteBuffer(BinaryWriter os, byte[] array) { if ((array!=null) && (array.Length > 0) && (array.Length < MAX_BUFFER_SIZE)) { WriteInt(os,array.Length); os.Write(array); } else { WriteInt(os,0); } } public static void WriteInt(BinaryWriter outStream, int value) { byte[] buffer = BitConverter.GetBytes(value); // Array.Reverse(buffer); outStream.Write(buffer); }