Java 网络编程简单实现

Java 网络编程笔记

1. 获取终端信息

在获取终端信息时,需要使用InetAddress类的相应方法进行获取

1.1 获取本机的网络相关信息

获取本机的网络相关信息时需要使用命令InetAddress.getLocalHost()
获得InetAddress类型的实例对象引用。
然后,可以使用以下方法获取需要的数据


.getHostName();//获取本机名
.getHostAddress();//获取本机地址
.

2.Socket编程

2.1 实现原理:

在进行Socket编程之前需要了解C/S(客户端/服务器)通信的实现原理:
首先,需要为服务器指定端口号,然后,循环检测端口,等待客户机发出
请求进行连接;同时,客户端程序需要知道服务器端的ip和相应通信程
序的端口号,然后发起连接请求从而进行连接.

通常的网络编程往往会涉及到服务器和客户机,而在多台终端进行通信
时,除了需要知道彼此之间的IP外,还需要知道通信程序的端口号.

所以在进行Socket编程时,需要指定通信的端口号.

2.2 信息传输

信息传输时使用的数据流一般有两种:

  • DataInputStream:数据输入流(相对于当前程序讲的,接收的数据通过数据输入流进行接收)
  • DataOutputStream:数据输出流(相对于当前程序讲的,输出的数据通过数据输出流进行输出)

流对象引用的获取

  • DataInputStream dis = new DataInputStream(Socket.getInputStream());
  • DataOutputStream dos = new DataOutputStream(Socket.getOutputStream());

流对象的使用:

  • dis.readUTF():读取流中的数据(dis:DataInputStream 实例对象引用,
    dis的read方法的类型用很多).
  • dos.writeUTF():输出信息(dis:DataOutputStream 实例对象引用,
    dos的write方法的类型用很多)。

实例演示:

功能:
服务器server,客户端clent,
服务器将从客户端接收的数据返回给client

Servlet:
包含三部分:
1.创建套接字和流对象(实例化过程需要使用try-catch块进行包裹)

  • 套接字包含两个:
    - 服务器端套接字
    - 客户端套接字

  • 流对象包含两个:
    - 输入流DataInputStream
    - 输出流DataOutputStream

2.实例化对象,接收客户端套接字连续呼叫
3.进行通信


public class Server {
	public static void main(String args[]){
		ServerSocket server = null;
		Socket client = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		try{
			server = new ServerSocket(8888);
			client = server.accept();//接收客户端套接字连续呼叫
			dis = new DataInputStream(client.getInputStream());
			dos = new DataOutputStream(client.getOutputStream());
			//通信
			while(true){
				str = in.readUTF();
				dos.writeUTF("hello clients");
				dos.writeUTF("server get client\' info"+str)
				sleep(1000);//线程修眠
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

Client客户端:
1.定义套接字和数据流

  • 套接字:
    - 服务器端套接字

  • 数据流
    - DataInputStream
    - DataOutputStream
    2.实例化套接字
    3.通信

public class Client{

	public static void main(String args[]){
		//1
		Socket client = null;
		DataInputStream dis = null;
		DataOutputStream dos = null;
		
		try{
			//2
			client = new Socket("127.0.0.1",8888);//ip,端口号
			dis = new DataInputStream(client.getInputStream());
			dos = new DataOuputStream(client.getOutputStreams());
			//3
			while(true){
				String server_str = dis.readUTF();
				System.out.println("server:"+server_str);
				dos.writeUTF((int)(Math.random()*10+1)+"");
				sleep(1000);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹振坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值