我最初尝试连接到端口9090
,但它引发了异常。然后,我尝试了另一个端口号61231
,它再次引发了异常。 (这就是我初始化端口的方式)
ServerSocket listener = new ServerSocket(61231);
我也知道服务器上有哪些可用端口。
当我在Java DataServer
终端上进行linux
时
Exception in thread "main" java.net.BindException: Address already in use (Bind failed)
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at DataServer.main(DataServer.java:15)
DataServer.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/*A TCP server that runs on port 9090.
When a client connects, it sends the
client the current date and time, then
closes the connection with that client.*/
public class DataServer {
/*** Runs the server.*/
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(61231);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
DataClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.swing.JOptionPane;
public class DataClient {
/*** Runs the client as an application.
* First it displays
* a dialog box asking for the IP address or hostname
* * of a host running the date server, then connects to
* * it and displays the date that it serves.*/
public static void main(String[] args) throws IOException {
// String serverAddress = JOptionPane.showInputDialog(
// "Enter IP Address of a machine that is\n" +
// "running the date service on port 9090:");
System.out.print("Please input the server address:");
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//Reading data using readLine
String serverAddress = reader.readLine();
Socket s = new Socket(serverAddress, 61231);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println("Reply" + answer);
//JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}