Java 网络编程回顾

URL的使用

url = new URL("http://www.google.cn");
HttpURLConnection httpUrl = (HttpURLConnection) url
		.openConnection();//打开 URL 获取 HTTP 特定功能的 URLConnection
BufferedReader br = new BufferedReader(new InputStreamReader(
					httpUrl.getInputStream()));//读取文件流

 使用TCP 传输

serverSocket = new ServerSocket(1444);
Socket socket = serverSocket.accept();// 获取socket
// PrintWriter os = new
// PrintWriter(socket.getOutputStream());//创建发送数据的数据流
// os.print("socketServer 发出的消息,"
// + dateFormate.format(new Date()));// 发送消息
// os.flush();
// System.out.println("socketServer Server 发出的消息: "
// + dateFormate.format(new Date()));

BufferedReader is = new BufferedReader(new InputStreamReader(socket
		.getInputStream()));// 创建接收数据的数据流
String tempString = null;
while ((tempString = is.readLine()) != null) {// 一行行读取数据
	System.out.println("socketServer收到的消息: " + tempString);
}
// os.close();
is.close();
socket.close();

 使用UDP

         public void run() {
		byte[] byteTemp = new byte[256];
		dataSocket = new DatagramSocket(1444);//这里仅指定端口,ip 包括在数据包中
		DatagramPacket dataPacket = new DatagramPacket(byteTemp,256);//创建数据包
		String info = "UDPClient 发送的消息";//每次消息在64kb以内
		try {
			dataPacket.setData(info.getBytes());
			dataPacket.setAddress(InetAddress.getByName("127.0.0.1"));
			dataSocket.send(dataPacket);//发送数据包
			System.out.println("UDPClient 发送消息成功.");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		dataSocket.close();
	}
 
	public void run() {
		byte[] byteTemp = new byte[256];
		dataSocket = new DatagramSocket(1444);//这里仅指定端口,ip 包括在数据包中
		DatagramPacket dataPacket = new DatagramPacket(byteTemp,256);//定义数据包
		try {
			dataSocket.receive(dataPacket);//接收煤炭数据包
			String receive = new String(dataPacket.getData());
			System.out.println("UDPServer 接收到的消息: " + receive);
			System.out.println("UDPServer 接收消息成功.");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		dataSocket.close();
	}
 

你可能感兴趣的:(java,编程,socket,Google,OS)