java socket(3)
import java.net.*;
import java.io.*;
public class PortScanner {
public static void main(String args[]){
String host="localhost";
if(args.length>0)host=args[0];
new PortScanner().scan(host);
}
public void scan(String host){
Socket socket=null;
for(int port=1;port<1024;port++){
try {
socket = new Socket(host, port);
System.out.println("There is a server on port "+port);
} catch (IOException e) {
System.out.println("Can't connect to port "+port);
} finally {
try {
if(socket!=null)socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package ch02;
import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ConnectTest {
public static void main(String[] args) {
String host = "www.baidu.com";
int port = 80;
if (args.length > 1) {
host = args[0];
port = Integer.parseInt(args[1]);
}
new ConnectTest().connect(host, port);
}
private void connect(String host, int port) {
SocketAddress remoteAddress = new InetSocketAddress(host, port);
Socket socket = null;
String result;
try {
long begin = System.currentTimeMillis();
socket = new Socket();
socket.connect(remoteAddress, 1000);
long end = System.currentTimeMillis();
result = (end - begin) + "ms";
} catch (BindException e) {
result = "Local Address and port cant't be binded";
} catch (UnknownHostException e) {
result = "UnknownHost";
} catch (ConnectException e) {
result = "Connection Refused";
} catch (SocketException e) {
result = "Time out";
} catch (IOException e) {
result = "failure";
} finally {
if (socket != null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(remoteAddress + ":" + result);
}
}
Result:
package ch02;
import java.io.IOException;
import java.net.ServerSocket;
public class SimpleServer {
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket=new ServerSocket(8000,2);
new Thread().sleep(3600);
}
}
package ch02; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class SimpleClient { public static void main(String[] args) throws UnknownHostException, IOException { Socket socket1=new Socket("localhost",8000); System.out.println("first connect success"); Socket socket2=new Socket("localhost",8000); System.out.println("second connect success"); Socket socket3=new Socket("localhost",8000); System.out.println("third connect success"); } }