Java网络编程
1.一台JVM和另外一台JVM通信就要采用网络编程,此时必须知道要通信的JVM的IP地址和端口;
2.Java的网络编程提供了TCP和UDP两种方式其中TCP基于“三次握手”的方式建立起可靠的网络传输协议,UDP并不一定保证发送出去的数据会被接收到,网络上的聊天工具一般都会采用UDP;TCP更安全,UDP速度快;
3.基于TCP的网络的编程,主要是基于Socket进行编程,服务端是SocketServer会等待客户端的连接,客户端本身就是一个Socket;

/**
*获取IP地址,简单内容示例
* @throws Exception
*/
public static void getIp() throws Exception{
InetAddress local = null;
InetAddress remote = null;
local = InetAddress.getLocalHost(); //返回本地主机
//在给定主机名的情况下确定主机的 IP 地址。
//主机名可以是机器名(如 "java.sun.com"),也可以是其 IP 地址的文本表示形式。如果提供字面值 IP 地址,则仅检查地址格式的有效性。
remote = InetAddress.getByName("spark.apache.org");
System.out.println("Local IP: "+local.getHostAddress()); //返回IP地址字符串(以文本表现形式)
System.out.println("Spark IP: "+ remote.getHostAddress());//返回IP地址字符串(以文本表现形式)
URL url = new URL("http://spark.apache.org");
InputStream inputStream = url.openStream();
Scanner sc = new Scanner(inputStream);
sc.useDelimiter("\n"); //设置输入的分隔符
while (sc.hasNext()){
System.out.println(sc.next());
}
}
/**
* 获取内容的长度和类型,简单内容示例
* @throws Exception
*/
public static void getType() throws Exception{
URL url = new URL("http://spark.apache.org");
URLConnection urlConnection = url.openConnection();
System.out.println("The length: "+urlConnection.getContentLength());
System.out.println("The Content Type: "+urlConnection.getContentType());
}
/**
* Socket编程,简单内容示例
* @throws Exception
*/
public static void socketClient() throws Exception{
ServerSocket server = null;
Socket client = null;
PrintStream output = null;
server = new ServerSocket(9999);
System.out.println("------------It's ready to accept client's request-------------");
client = server.accept();
output = new PrintStream(client.getOutputStream());
output.println("I get it!");
output.close();
client.close();
server.close();
}
public static void getMessage() throws Exception{
Socket client = null;
client = new Socket("localhost",9999);
BufferedReader bufferedReader = null;
bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("The content from server is : "+bufferedReader.readLine());
bufferedReader.close();
client.close();
}
4.在服务端使用线程池来并发处理多个业务;

本文深入探讨了Java网络编程的核心概念,包括TCP和UDP的区别,Socket编程的基本原理,以及如何在服务端使用线程池处理并发请求。通过具体示例展示了如何获取IP地址,解析HTTP内容,以及实现简单的Socket客户端和服务端交互。
3万+

被折叠的 条评论
为什么被折叠?



