[英]Connection refused: connect error
我正在嘗試將文本文件從發送方發送到接收方,但是在發送方,我被拒絕連接:連接。 我在接收方使用本地主機地址,並在發送方提示時手動輸入本地主機地址。 該錯誤發生在發件人類的sendChannel.connect(address)處。
發件人類別:
public static void startProcess(){
SocketChannel sendChannel = null;
RandomAccessFile f = null;
Scanner scan = new Scanner(System.in);
SocketAddress address = null;
try{
sendChannel = SocketChannel.open(); // open the channel
//DatagramSocket socket = dChannel.socket();
boolean validAddr = false;
while(validAddr != true){
try{
System.out.println("Enter in valid server IP Address");
address = new InetSocketAddress(scan.nextLine(),7777);
validAddr = true;
}
catch(Exception e){
System.out.println("Invalid!");
System.out.println(e.getMessage());
}
}
//System.out.println("Address: " + InetAddress.getLocalHost().getHostAddress());
sendChannel.connect(address);
File i = new File("./data.txt");
f = new RandomAccessFile(i,"r");
FileChannel fChannel = f.getChannel();
ByteBuffer bBuffer = ByteBuffer.allocate(1024); //set buffer capacity to 1024 bytes
while (fChannel.read(bBuffer) > 0) {
//SocketAddress client = dChannel.receive(bBuffer); //receive the datagram
bBuffer.flip(); //Set limit to current position
sendChannel.write(bBuffer);
//dChannel.send(bBuffer, client); //send the datagram using channel
bBuffer.clear(); //Get ready for new sequence of operations
}
Thread.sleep(1000);
System.out.println("End of file reached");
sendChannel.close();
f.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
接收方:
public static void startProcess(){
Scanner scan = new Scanner(System.in);
ServerSocketChannel serverChannel = null;
SocketChannel chan = null;
RandomAccessFile file = null;
try{
serverChannel = ServerSocketChannel.open();
//Read in a valid IP Address
boolean val2 = false;
int tempNum = 0;
for (int portNUM = 7777 ;!val2; portNUM++){
try {
serverChannel.socket().bind(new InetSocketAddress("localhost", portNUM));
tempNum = portNUM;
val2 =true;
} catch (IOException e) {
System.out.println("Error!");
}
}
System.out.println(InetAddress.getLocalHost().getHostAddress());
System.out.println("Port Number: " + tempNum);
chan = serverChannel.accept();
System.out.println("Connected!");
chan.getRemoteAddress();
file = new RandomAccessFile("./output.txt","rw");
ByteBuffer buff = ByteBuffer.allocate(1024);
FileChannel receiveChannel = file.getChannel();
while(chan.read(buff) > 0){
buff.flip();
receiveChannel.write(buff);
buff.clear();
}
// buff.put((byte)65 );
//buff.flip();
Thread.sleep(1000);
receiveChannel.close();
System.out.println("End of file");
chan.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
我發現我在接收方錯誤地使用了本地主機。 我將其更改為serverChannel.socket()。bind(new InetSocketAddress(portNUM));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.