我正在尝试用Java创建一个简单的应用程序以将消息发送到服务器。当我运行该应用程序时,虽然没有使用端口4344的进程(我尝试更改端口号,但始终会抛出异常),但服务器上出现BindException(地址已在使用中)。尽管如此,该消息仍会到达服务器并显示该消息。
服务器代码:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import javax.swing.JOptionPane;
public class Server implements Runnable {
public static void main(String[] args){
Server s = new Server();
s.run();
}
public Server() {
Thread serverThread = new Thread(this);
serverThread.start();
}
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(4344);
while(true) {
Socket clientSocket = serverSocket.accept();
DataInputStream inputSocket = new DataInputStream(clientSocket.getInputStream());
System.out.println(inputSocket.readUTF());
inputSocket.close();
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户代码:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class Client {
Socket serverConnection;
String serverIp = "192.168.182.1";
public static void main(String[] args){
Client c = new Client();
}
public Client() {
sendMessage("message");
}
public void sendMessage(String msg) {
try {
serverConnection = new Socket(serverIp, 4344);
DataOutputStream dataOutput = new DataOutputStream(serverConnection.getOutputStream());
dataOutput.writeUTF(msg);
dataOutput.close();
serverConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}