Hi all,
I'm try to write a basic server-client java application. However, I alway got a message of "socket bind on 10 for port 13244 failed: Address already in use (errno=98)" error no matter what port I'm using.
I have attach a source code of my application, just wondering is there very stupid mistake I'm making.
Many Thanks!
Cheers, J
/**
* Command process test.
*/
import java.net.*;
import java.io.*;
public class CommandProcessTest implements Runnable{
private static final int PORT = 13244;
private ServerSocket serverSocket;
public static void main(String[] args) {
CommandProcessTest test = new CommandProcessTest();
System.out.println("starting server.");
test.start();
System.out.println("server start up.");
// try {
// test.wait(100);
// } catch(InterruptedException e) {
// }
// Thread client = new Thread(test);
System.out.println("Server start receiving.");
test.start();
System.out.println("Server exit.");
}
private void start() {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
}
private void server() {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
CommandProcess cp = new CommandProcess(clientSocket);
int cmd = 10;
String arg = "";
cp.sendCommand(cmd);
arg = "hello";
cp.sendCommand(cmd, arg.split(" "));
arg = "hello world";
cp.sendCommand(cmd, arg.split(" "));
arg = "world hello world";
cp.sendCommand(cmd, arg.split(" "));
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
private void client() {
try {
Socket socket = new Socket("localhost", PORT);
CommandProcess cp = new CommandProcess(socket);
while(true) {
int cmd = cp.getCommand();
String[] args = cp.getArguments();
String s = "Command: " + Integer.toString(cmd);
if(args != null) {
for(int i = 0; i < args.length; i++) {
if(args[i] == null) {
break;
}
s += args[i];
}
}
System.out.println(s);
}
} catch(IOException e) {
System.out.println("Would not connect to local host: 444");
System.exit(-1);
}
}
public void run() {
System.out.println("Starting client");
client();
System.out.println("Client startup.");
}
}