使用java程序连接网络
建立与主机的连接。
Socket s = new Socket("localhost",8080);
用这个方式建立与主机的连接,会一直堵塞下去,直到建立了到达主机的初始连接为止。改进方式:
Socket s = new Socket();
s.connect(new InetSocketAddress(host,port),timeout);
1、因特网地址
使用java程序可以获得任意域名对应的IP地址。
public class InetAddressTest {
public static void main(String[] args) throws UnknownHostException {
//获取百度域名对应的主机IP
InetAddress[] addresses = InetAddress.getAllByName("www.baidu.com");
for(InetAddress address : addresses){
System.out.println(address.getHostAddress());
}
//获取本机IP
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
}
}
结果:
119.75.216.20
119.75.213.61
lenovo-PC/172.20.51.173
2、搭建简易服务器
public class Server {
public static void startServer(int port) throws IOException{
//搭建服务监听port端口
ServerSocket sc = new ServerSocket(port);
while(true){
//获得客户端连接
Socket soc = sc.accept();
System.out.println("接入新连接:"+soc);
//多线程处理每一个客户端连接
new ClientHandler(soc).start();
}
}
public static void main(String[] args) throws IOException {
//启动服务
startServer(8989);
}
static class ClientHandler extends Thread {
Socket soc = null;
public ClientHandler(Socket soc) {
this.soc = soc;
}
@Override
public void run() {
if(this.soc !=null){
//获得输入流与输出流
try(InputStream inStream = soc.getInputStream();
OutputStream outStream = soc.getOutputStream();){
Scanner in = new Scanner(inStream,"UTF-8");
//输出流自动刷新,不必使用flush方法
PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream), true);
out.println("Hello!enter BYE to exit");
boolean done = true;
while(done&&in.hasNextLine()){
String line = in.nextLine();
out.println(line);
if(line.trim().equals("BYE")){
done = false;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
效果:
启动一个命令行窗口,使用命令telnet localhost 8989连接服务器。
连接服务器后,你输入什么,屏幕上回显什么,直到你输入BYE,断开连接。