我最近开始学习java。我正在编写一个带有“聊天”的Android应用程序。特征。我想要一个java聊天服务器,客户端代码将来自C#。这是Java服务器代码,
import java.net.*;
import java.io.*;
public class server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
public server(int port)
{
try
{
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open(); // Custom method
boolean done = false;
while(!done)
{
try
{
String line = streamIn.readUTF();
System.out.println(line);
done = line.equals(".bye");
}
catch(IOException ioe)
{
done = true;
}
}
close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
private void close() throws IOException
{
if (socket != null) socket.close();
if(streamIn != null) streamIn.close();
}
public void open() throws IOException
{
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//streamOut = new DataOutputStream(socket.getOutputStream());
//streamOut.writeUTF("Hello");
//streamOut.flush();
//System.out.println("Message sent");
}
public static void main(String args[])
{
server ss = null;
if(args.length != 1)
{
System.out.println("Usage: java ChatServer port");
}
else
{
ss = new server(Integer.parseInt(args[0]));
}
}
}
上面的代码是使用eclipse运行的,我在C#客户端应用程序中使用了networkstream和StreamReader,但是我可以使用TCPClient连接到服务器,但是流读取器或网络流没有工作。
C#代码
private static TcpClient client;
private static BinaryWriter writer;
private const int MAX_BUFFER_SIZE = 1024;
private static void Main(string[] args)
{
try
{
Console.WriteLine("Connecting to the server");
client = new TcpClient();
client.Connect("127.0.0.1", 8888);
writer = new BinaryWriter(client.GetStream());
Console.WriteLine("Connected to the server");
Console.WriteLine("Sending hello world");
WriteString(writer, "Hello World!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
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);
outStream.Write(buffer);
}
以上代码来自link 我也在堆栈中找到了一些使用网络流的代码,但我没有运气。我已经使用StreamWriter / reader编写了一个C#聊天应用程序。任何帮助表示赞赏/。服务器工作,java客户端正在与它很好地工作。 (我对C#有一点经验,但对Java没有经验)
由于
编辑: - 我发现它与类使用的编码差异有关。 Source