JAVA 网络编程

来源:互联网 发布:armageddon软件 编辑:程序博客网 时间:2024/06/07 11:32

一、网络编程相关

IP地址:网络中设备的标识,不易记忆,可用主机名
本地地址:127.0.0.1  主机名:localhost
端口(逻辑端口 ):
用于标识进程的逻辑地址,不同进程的标识
有效端口:0~65535,其中0~1024系统使用或保留端口。
计算机间通讯实质是两个进程间的通讯,而IP地址标示计算机物理设备,端口号就是标示具体进程

如图中每个设备发出的数据包中都包含有类似IP=XXX,端口=XXX,这样就等定位到要通讯的具体设备中的具体进程,而具体实现就要用到java中的Socket类了。
Socket套接字
Socket是应用层与TCP/IP协议族通信的中间软件抽象层,把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。
传输协议(通讯的规则)
常见协议:TCP/IP,UDP
一.区别
二者都是有用的和常用的,如果纯粹从概念上区分二者就比较费解了,我们直接从功能上进行区分,简单明了: 
这两种传输协议也就是合于适配不同的业务和不同的硬件终端。 
在使用中,类似于图像、声音等对可靠性要求没有那么高的业务可以用UDP,他们不需要准确存储对准确性无要求但要求速度快。
类似于文本、程序、文件等要求可靠的数据最好就用TCP,但会牺牲一些速度。 
对系统资源的要求:CP较多,UDP少。 
程序结构:UDP程序结构较简单,TCP复杂。 
流模式与数据报模式:TCP保证数据正确性,UDP可能丢包; TCP保证数据顺序,UDP不保证
 
二.用途
TCP是面向连接的,有比较高的可靠性,一些要求比较高的服务一般使用这个协议,如FTP、Telnet、SMTP、HTTP、POP3等,而 UDP是面向无连接的,使用这个协议的常见服务有DNS、SNMP、QQ等。对于QQ必须另外说明一下,QQ2003以前是只使用UDP协议的,其服务器 使用8000端口,侦听是否有信息传来,客户端使用4000端口,向外发送信息(这也就不难理解在一般的显IP的QQ版本中显示好友的IP地址信息中端口 常为4000或其后续端口的原因了),即QQ程序既接受服务又提供服务,在以后的QQ版本中也支持使用TCP协议了。 
UDP是一种面向无连接的通信协议,该协议使得数据传输的速度得到大幅度的提高。视频聊天语音聊天基本都是用UDP协议。 



二、常见的两种通讯协议实现代码

  • UDP
接受键盘录入字符串并发送到本机127.0.0.1的8888端口
public class UdpSend {public static void main(String[] args) throws Exception {DatagramSocket socket = new DatagramSocket();DatagramPacket packet;BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String line;while ((line = reader.readLine()) != null && !"886".equals(line)) {packet = new DatagramPacket(line.getBytes(),line.getBytes().length, InetAddress.getByName("127.0.0.1"),8888);socket.send(packet);}socket.close();}}
接受8888端口的数据,并打印来源ip和端口
public class UdpReceive {public static void main(String[] args) throws Exception{DatagramSocket socket=new DatagramSocket(8888);while(true){byte[] buf=new byte[1024];DatagramPacket packet=new DatagramPacket(buf, buf.length);socket.receive(packet);String ip=packet.getAddress().getHostAddress();System.out.println(ip);System.out.println(packet.getPort());System.out.println(new String(packet.getData()));}}}
多线程模拟聊天过程,一个线程接受、一个线程发送
public class Chat {public static void main(String[] args) throws Exception {Send send = new Send();Receive receive = new Receive();send.setSocket_send(new DatagramSocket());receive.setSocket_receive(new DatagramSocket(9999));Thread t1 = new Thread(send);Thread t2 = new Thread(receive);t1.start();t2.start();}}class Send implements Runnable {private DatagramSocket socket_send;public void setSocket_send(DatagramSocket socket_send) {this.socket_send = socket_send;}public DatagramSocket getSocket_send() {return socket_send;}@Overridepublic void run() {// TODO Auto-generated method stubDatagramPacket packet;BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String line;try {while ((line = reader.readLine()) != null) {packet = new DatagramPacket(line.getBytes(),line.getBytes().length,InetAddress.getByName("127.0.0.1"), 9999);socket_send.send(packet);if ("bye".equals(line))break;}socket_send.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}class Receive implements Runnable {private DatagramSocket socket_receive;public void setSocket_receive(DatagramSocket socket_send) {this.socket_receive = socket_send;}@Overridepublic void run() {// TODO Auto-generated method stubDatagramPacket packet;byte[] buf = new byte[1024];try {while (true) {packet = new DatagramPacket(buf, buf.length);socket_receive.receive(packet);System.out.println(new String(packet.getData()));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
  • TCP/IP
客户端接收键盘录入发送数据给127.0.0.1本机的2015端口
public class TCPClient {public static void main(String[] args) throws Exception {ServerSocket serSocket = new ServerSocket(2015);Socket socket = serSocket.accept();InetAddress inetAddress = socket.getInetAddress();System.out.println(inetAddress.getHostAddress() + "连接中...");InputStream in = socket.getInputStream();byte[] buf = new byte[1024];int len = 0;while ((len = in.read(buf)) != -1) {System.out.println(new String(buf, 0, len));}serSocket.close();}}
服务器端接受数据并打印
public class TCPServer {public static void main(String[] args) throws Exception {Socket socket = new Socket("127.0.0.1", 2015);OutputStream out = socket.getOutputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String data = null;while ((data = reader.readLine()) != null) {out.write(data.getBytes());}socket.close();}}
客服端上传图片到服务器并接受服务器反馈信息并打印
public class TCPPicC {public static void main(String[] args) throws Exception {File file = new File("d:" + File.separator + "heima.jpg");Socket socket = new Socket("127.0.0.1", 2015);BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));OutputStream out =  socket.getOutputStream();byte[] data = new byte[1024];int lens=0;while ((lens=in.read(data)) != -1) {out.write(data,0,lens);}socket.shutdownOutput();in.close();InputStream inputStream=socket.getInputStream();byte[] buf=new byte[1024];int len=inputStream.read(buf);System.out.println(new String(buf, 0, len));socket.close();}}
服务器端接收客户端上传的图片并反馈信息给客户端
public class TCPPicS {public static void main(String[] args) throws Exception {ServerSocket serverSocket = new ServerSocket(2015);Socket socket = serverSocket.accept();BufferedInputStream in = new BufferedInputStream(socket.getInputStream());BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:" + File.separator + "heima111.jpg"));int data = 0;while ((data = in.read()) != -1) {out.write(data);}OutputStream outputStream=socket.getOutputStream();outputStream.write("接收完毕".getBytes());out.close();serverSocket.close();}}


0 0
原创粉丝点击