如何解决Java socket 端口复用调用connect方法时的:invalid argument问题?
刚学java socket编程,轻喷
server side防火墙打开
client side防火墙打开
server side两个端口有serversocket listen
client side用两个socket实现端口复用后分别连接serversocket端口时
client side挂掉了
//client side// import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetSocketAddress;
// import java.io.InputStreamReader;
// import java.net.ServerSocket;
import java.net.Socket;
import java.net.StandardSocketOptions;
import java.net.UnknownHostException;
public class TestTcp {
public static void main(String args[]) throws UnknownHostException, IOException
{
Socket failhelp=new Socket();
failhelp.setOption(StandardSocketOptions.SO_REUSEADDR, true);
failhelp.setOption(StandardSocketOptions.SO_REUSEPORT, true);
// testsuc.bind(new InetSocketAddress("localhost", failhelp.getLocalPort()));
failhelp.connect(new InetSocketAddress("ServerIp",5130));
Socket testsuc=new Socket();
testsuc.setOption(StandardSocketOptions.SO_REUSEADDR, true);
testsuc.setOption(StandardSocketOptions.SO_REUSEPORT, true);
testsuc.bind(new InetSocketAddress("localhost", failhelp.getLocalPort()));
testsuc.connect(new InetSocketAddress("ServerIp",39001));
//可以绑一个端口了
//但是报错invalid argument
testsuc.close();
failhelp.close();
// listener.close();
System.out.println("SUC\n");
}
}
//文明的曙光了属于是
//只要实现了一榜多,那么理论上是可以实现的
//1. 服务器一个,先连接
//2. 交换A,B公网地址和端口
//3. A,B引线多绑server
//4. A,B对发,只要不被都丢掉就行
//server sideimport java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.StandardSocketOptions;
public class Test {
public static void main(String args[]) throws IOException, InterruptedException
{
ServerSocket listener=new ServerSocket(5130);
ServerSocket gngd=new ServerSocket(39001);
Socket failhelp=listener.accept();
failhelp.setOption(StandardSocketOptions.SO_REUSEADDR, true);
failhelp.setOption(StandardSocketOptions.SO_REUSEPORT, true);
// Socket rnmmp=new Socket(failhelp.getInetAddress(),failhelp.getPort(),failhelp.getLocalAddress(),failhelp.getLocalPort());
Socket fuck=gngd.accept();
System.out.println("SUC\n");
listener.close();
failhelp.close();
fuck.close();
gngd.close();
}
}
报错:
Exception in thread "main" java.net.SocketException: Invalid argument at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:585)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at java.base/java.net.Socket.connect(Socket.java:583)
at TestTcp.main(TestTcp.java:24)//具体在testsuc.connect(...)时出问题
以上是 如何解决Java socket 端口复用调用connect方法时的:invalid argument问题? 的全部内容, 来源链接: utcz.com/p/944792.html