gpt4 book ai didi

Java Socket 服务器和 C# 客户端本地主机可以工作

转载 作者:行者123 更新时间:2023-12-02 01:53:35 25 4
gpt4 key购买 nike

我有一个 C# 客户端,它将数据发送到 Java 异步服务器并在 GUI 中写入数据,在 localhost 中一切正常,但是,当我更改为其他 ip 时,客户端我说:

System.Net.Sockets.SocketException (0x80004005): Unable to establish a connection since the destination equipment expressly denied such connection 192.168.1.172:11000 en System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) en System.Net.Sockets.Socket.Connect(EndPoint remoteEP)

客户端 C#:

public void StartClient(string precio)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];

// Connect to a remote device.
try
{

IPAddress ipAddress = IPAddress.Parse("192.168.1.172");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);

// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);

Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());

// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(precio + "<EOF>");
Console.WriteLine(msg);
// Send the data through the socket.
int bytesSent = sender.Send(msg);

// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();

}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

Java 服务器:

    private void init() throws IOException, InterruptedException {
AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();//w w w . j a v a2s .com
String host = "127.0.0.1";
int port = 11000;
InetSocketAddress sAddr = new InetSocketAddress(host, port);
server.bind(sAddr);
System.out.format("Server is listening at %s%n", sAddr);
Attachment attach = new Attachment();
attach.server = server;
server.accept(attach, new ConnectionHandler());
//Thread.currentThread().join();
}


}
class Attachment {
AsynchronousServerSocketChannel server;
AsynchronousSocketChannel client;
ByteBuffer buffer;
SocketAddress clientAddr;
boolean isRead;
}

class ConnectionHandler implements
CompletionHandler<AsynchronousSocketChannel, Attachment> {
@Override
public void completed(AsynchronousSocketChannel client, Attachment attach) {
try {
SocketAddress clientAddr = client.getRemoteAddress();
System.out.format("Accepted a connection from %s%n", clientAddr);
attach.server.accept(attach, this);
ReadWriteHandler rwHandler = new ReadWriteHandler();
Attachment newAttach = new Attachment();
newAttach.server = attach.server;
newAttach.client = client;
newAttach.buffer = ByteBuffer.allocate(2048);
newAttach.isRead = true;
newAttach.clientAddr = clientAddr;
client.read(newAttach.buffer, newAttach, rwHandler);
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void failed(Throwable e, Attachment attach) {
System.out.println("Failed to accept a connection.");
e.printStackTrace();
}
}

class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
@Override
public void completed(Integer result, Attachment attach) {
if (result == -1) {
try {
attach.client.close();
System.out.format("Stopped listening to the client %s%n",
attach.clientAddr);
} catch (IOException ex) {
ex.printStackTrace();
}
return;
}

if (attach.isRead) {
attach.buffer.flip();
int limits = attach.buffer.limit();
byte bytes[] = new byte[limits];
attach.buffer.get(bytes, 0, limits);
Charset cs = Charset.forName("UTF-8");
String msg = new String(bytes, cs);
if (msg.contains("<EOF>")){
//System.out.println("es Total");
Servidor.total = msg.substring(0,msg.indexOf("<"));
Servidor.formEntrada.setLabelTotal(Servidor.total);
Servidor.total = Servidor.total.replace(",",".");
//onSendData.onSendDataTotal();
}else if (msg.contains("<REC>")) {
//System.out.println("es Cobro");
Servidor.enviado = msg.substring(0, msg.indexOf("<"));
Servidor.formEntrada.setLabelEnviado(Servidor.enviado);
Servidor.enviado = Servidor.enviado.replace(",", ".");
if (Double.parseDouble(Servidor.enviado) >= Double.parseDouble(Servidor.total)) {
Servidor.formEntrada.setRestoValue(Servidor.total, Servidor.enviado);
}
}
System.out.format("Client at %s says: %s%n", attach.clientAddr,
msg);
attach.isRead = false; // It is a write
attach.buffer.rewind();

} else {
// Write to the client
attach.client.write(attach.buffer, attach, this);
attach.isRead = true;
attach.buffer.clear();
attach.client.read(attach.buffer, attach, this);
}
}

@Override
public void failed(Throwable e, Attachment attach) {
e.printStackTrace();
}

为什么它只能在本地主机上工作?

最佳答案

好吧,您只绑定(bind)到localhost。您应该使用要绑定(bind)的实际 IP 地址。

您还可以尝试通过以下方式绑定(bind)到所有 IPv4 接口(interface):

InetSocketAddress sAddr = new InetSocketAddress("0.0.0.0", port);
server.bind(sAddr);

关于Java Socket 服务器和 C# 客户端本地主机可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52628837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com