java Socket编程总结

来源:互联网 发布:怎样做好淘宝网店 编辑:程序博客网 时间:2024/06/04 23:02

看了毕向东的java网络编程,做一下总结

1.获取本地主机的IP地址对象

用的是InetAddress类,先来看看这个类吧。
java.lang.Object
  java.net.InetAddress
直接已知子类: 
Inet4Address, Inet6Address


静态方法
static InetAddress getLocalHost(),返回本地主机,打印出来的是本机的计算机名和IP地址。

String getHostAddress() :返回ip地址字符串。

String getHostName():获取此IP地址的主机名。






static InetAddress getByName(String host):在给定主机名的情况下确定主机的IP地址


代码:
//获取本地主机IP地址对象
InetAddress ip = InetAddress.getLocalHost();
//获取其他主机的IP地址对象
ip = InetAddress.getByName("192.168.1.109");//InetAddress.getByName("SDWM-20130713PS");
System.out.println(ip.getHostAddress());
System.out.println(ip.getHostName());
System.out.println(ip);


打印的结果是:192.168.1.109
     www.lgh.com
     www.lgh.com/192.168.1.109
若屏蔽  System.out.println(ip.getHostName());则打印的是:
      192.168.1.109
      /192.168.1.109

注意我在C:\Windows\System32\drivers\etc\hosts文件中加了192.168.1.109    www.lgh.com我觉得出现上述结果的原因应该是getHostName()做了些什么(拿到域名)。


2.域名解析

先到本地的hosts(C:\Windows\System32\drivers\etc)查找,找不到则到域名服务器中查找。比如:在浏览器上面输入网址,计算机先到hosts查找对应的IP地址,若本地没有则会到域名服务器(不同地方设置不同吧,好像有多个,如果这个没有则传给下一个DNS)查找。当我们想屏蔽一些网站比如弹窗游戏网站时可以利用这个原理在hosts文件中,或在自己添加的host文件中设置该网站的网址对应的IP为127.0.0.1(回环地址),这时候当浏览器试图打开这些网站时就会回到本机的IP上。360中的恶意屏蔽网址也是这样做的。hosts.bat.360中就有。


3.UDP协议-发送端

public static void main(String[] args) throws IOException {System.out.println("发送端启动.....");/* * 创建UDP传输的发送端 * 思路: * 1.建立udp的socket服务. * 2.将要发送的数据封装到数据包中 * 3.通过udp的socket服务将数据包发送出去 * 4.关闭socket服务 *///1.udpsocket服务。使用DatagramSocket对象。DatagramSocket ds = new DatagramSocket(8888);//2.将要发送的数据封装数据包中。String str = "udp传输演示:哥们来了!";//3.使用DatagramPacket将数据封装到该对象包中。byte[] buf = str.getBytes();DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.109"),10000);//4.通过udp的socket服务将数据包发送出去。使用ssend方法。ds.send(dp);//5.关闭资源ds.close();}}

4.UDP协议-接收端

public static void main(String[] args) throws IOException {System.out.println("接收端启动.......");/* * 建立UDP接收端的思路 * 1.建立udp socket服务,因为是要接收数据,必须要明确一个端口号 * 2.创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据。 * 3.使用socket服务的receive方法将接收的数据存储到数据包中。 * 4.通过数据包的方法解析数据包中的数据。 * 5.关闭资源 *///1.建立udp socket服务。DatagramSocket ds = new DatagramSocket(10000);//2.创建数据包。byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);//3.使用接收方法将数据存储到数据包中。ds.receive(dp);//阻塞式的。//4.通过数据包对象的方法,解析其中的数据。比如:地址、端口、数据内容。String ip = dp.getAddress().getHostAddress();int port = dp.getPort();String text = new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+port+":"+text);//5.关闭资源     //ds.close();}


5.键盘输入聊天发送端
public class UDPSendDemo2 {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException,UnknownHostException,SocketExceptio {System.out.println("发送端启动.....");/* * 创建UDP传输的发送端 * 思路: * 1.建立udp的socket服务. * 2.将要发送的数据封装到数据包中 * 3.通过udp的socket服务将数据包发送出去 * 4.关闭socket服务 *///1.udpsocket服务。使用DatagramSocket对象。DatagramSocket ds = new DatagramSocket(8888);//String str = "udp传输演示:哥们来了!";BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = bufr.readLine())!=null){byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.109"),10000);ds.send(dp);if("886".equals(line))break;}//5.关闭资源ds.close();}}

6.键盘输入聊天接收端(多了屏蔽close()和while(true))
public static void main(String[] args) throws IOException {System.out.println("接收端启动......");/* * 建立UDP接收端的思路。 * 1,建立udp socket服务,因为是要接收数据,必须要明确一个端口号。 * 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据. * 3,使用socket服务的receive方法将接收的数据存储到数据包中。 * 4,通过数据包的方法解析数据包中的数据。 * 5,关闭资源  *///1,建立udp socket服务。DatagramSocket ds = new DatagramSocket(10001);while(true){//2,创建数据包。byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);//3,使用接收方法将数据存储到数据包中。ds.receive(dp);//阻塞式的。//4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。String ip = dp.getAddress().getHostAddress();int port = dp.getPort();String text = new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+port+":"+text);}//5,关闭资源。//ds.close();}


7.6.开启多线程,群聊。
Send类:
package lgh.net;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class Send implements Runnable {private DatagramSocket ds;public Send(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {try {BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line=bufr.readLine())!=null){byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10001);ds.send(dp);if("886".equals(line))break;}ds.close();} catch (Exception e){}}}

Rece类:
package lgh.net;import java.net.DatagramPacket;import java.net.DatagramSocket;public class Rece implements Runnable {private DatagramSocket ds;public Rece(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {try {while (true) {byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();int port = dp.getPort();String text = new String(dp.getData(),0,dp.getLength());System.out.println(ip + ":" +port +":" + text);if(text.equals("886")){System.out.println(ip+"退出聊天室");}}}catch (Exception e) {}}}

ChatDemo类:
package lgh.net;import java.io.IOException;import java.net.DatagramSocket;public class ChatDemo {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {DatagramSocket send = new DatagramSocket();DatagramSocket rece = new DatagramSocket(10001);new Thread(new Send(send)).start();new Thread(new Rece(rece)).start();}}

其实跟上面的内容差不多,不过是开启了多线程在run函数里执行,局域网群聊就是把发送的IP改为广播IP,当你的电脑连了网线并开启了无线接收端就会收到两个发送端传来的信息,因为你的电脑占了两个IP(没错吧?)。
0 0
原创粉丝点击