网络通讯

1.要想实现网络传输,需要考虑的问题有哪些?
   1.1 如何才能准确的定位网络上的一台主机?
   1.2 如何才能进行可靠的、高效的数据传输?


2.java如何实现的网络通信
   2.1使用IP地址---定位一台主机    使用端口号---定位一个应用  ===>InetAddress类

        >如何创建一个InetAddress的对象?getByName("");   比如:InetAddress inet = InetAddress.getByName("192.168.10.165");
        >如何获取本机的一个InetAddress的对象?getLocalHost()
        >域名:getHostName()     ip:getHostAddress()
        
    TCP/IP协议,泛指,其中包括很多协议。
    包括:HTTP(属于应用层), TCP,UDP(属于传输层)。 IP(属于网络层)
    HTTP底层应用TCP协议进行数据传输。

package com.atguigu.java1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

//TCP编程例一:客户端给服务端发送信息。服务端输出此信息到控制台上
//网络编程实际上就是Socket的编程
public class TestTCP1 {

	// 客户端
	@Test
	public void client() {
		Socket socket = null;
		OutputStream os = null;
		try {
			// 1.创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
			socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
			// 2.getOutputStream():发送数据,方法返回OutputStream的对象
			os = socket.getOutputStream();
			// 3.具体的输出过程
			os.write("我是客户端,请多关照".getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 4.关闭相应的流和Socket对象
			try {
				if (os != null) {
					os.close();
				}
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 服务端
	@Test
	public void server() {
		ServerSocket ss = null;
		Socket s = null;
		InputStream is = null;
		try {
			// 1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
			ss = new ServerSocket(9090);
			// 2.调用其accept()方法,返回一个Socket的对象
			s = ss.accept();
			// 3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
			is = s.getInputStream();
			// 4.对获取的输入流进行的操作
			byte[] b = new byte[20];
			int len;
			while ((len = is.read(b)) != -1) {
				String str = new String(b, 0, len);
				System.out.print(str);
			}
			System.out.println("收到来自于" + s.getInetAddress().getHostAddress()
					+ "的连接");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 5.关闭相应的流以及Socket、ServerSocket的对象
			try {
				if (is != null) {
					is.close();
				}
				if (s != null) {
					s.close();
				}
				if (ss != null) {
					ss.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
}

 

转载于:https://my.oschina.net/u/3544282/blog/1377262

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值