我正在尝试设置C#所在的客户端 - 服务器通信 服务器端和Java是客户端。连接成功 我能够从C#发送一个字符串到Java。但是,我有 将字符串从Java发送到C#的问题。服务器没有得到任何 输入。
我的代码如下:服务器端C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ServerToJava
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(5678);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
NetworkStream networkStream = clientSocket.GetStream();
try
{
requestCount = requestCount + 1;
string serverResponse = "Last Message from client server This is a test";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
Console.Write ("ReadClient Thread started");
int length = networkStream.ReadByte ();
byte[] buffer = new byte[length];
int size = networkStream.ReadByte ();
byte[] buff = new byte[size];
using (var memoryStream = new MemoryStream(buff,false)) {
using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8)) {
var message = streamReader.ReadLine();
buff = Encoding.UTF8.GetBytes(message);
networkStream.Read(buffer, 0 ,buffer.Length);
Console.Write (message);
networkStream.Flush();
}
}
}
catch (Exception ex)
{
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
客户端Java
OutputStream out;
Socket s = new Socket("127.0.0.1", 5678);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
out= s.getOutputStream();
out.write('a');
System.exit(0);
答案 0 :(得分:0)
您不应该使用new TcpListener(5678)
已过时,而是使用以下内容:
// Set the TcpListener on port 5678.
Int32 port = 5678;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(localAddr, port);
来源`MSDN