欢迎来到天天文库
浏览记录
ID:10484457
大小:397.50 KB
页数:70页
时间:2018-07-06
《java_socket网络编程大全》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、1.简单服务器端/*importjava.net.*;importjava.io.*;*/ServerSocketserver=null;try{server=newServerSocket(%%1);}catch(Exceptione){System.out.println("不能监听:"+e.toString());}Socketsocket=null;try{socket=server.accept();BufferedReader%%3=newBufferedReader(newInputStre
2、amReader(socket.getInputStream()));PrintWriter%%4=newPrintWriter(socket.getOutputStream());String%%2=%%3.readLine();%%4.println("");%%4.flush();%%4.close();%%3.close();}catch(IOExceptione){System.out.println("出错:"+e.toString());}finally{try{if(socket!=nul
3、l){socket.close();server.close();}}catch(IOExceptione){e.printStackTrace();}}2.简单客户端/*importjava.net.*;importjava.io.*;*/Socketsocket=null;try{70(第页)socket=newSocket(%%1,%%2);PrintWriter%%3=newPrintWriter(socket.getOutputStream());BufferedReader%%4=newBuf
4、feredReader(newInputStreamReader(socket.getInputStream()));%%3.println("");%%3.flush();String%%5=%%4.readLine();%%6%%3.close();%%4.close();}catch(Exceptione){e.printStackTrace();}finally{try{socket.close();}catch(IOExceptione){e.printStackTrace();}}3.获得本机
5、IP//importjava.net.*;StringstrIP=null;try{strIP=InetAddress.getLocalHost().getHostAddress().toString();}catch(UnknownHostExceptione){e.printStackTrace();}/*%%1=InetAddress.getLocalHost().getHostAddress();EnumerationnetInterfaces=null;try
6、{netInterfaces=NetworkInterface.getNetworkInterfaces();while(netInterfaces.hasMoreElements()){NetworkInterfaceni=netInterfaces.nextElement();System.out.println("DisplayName:"+ni.getDisplayName());System.out.println("Name:"+ni.getName());Enumeration7、dress>ips=ni.getInetAddresses();while(ips.hasMoreElements()){70(第页)System.out.println("IP:"+ips.nextElement().getHostAddress());}}}catch(Exceptione){e.printStackTrace();}*/4.端对端通信//importjava.net.*;byte[]buf=newbyte[1024];DatagramSocketds=newDatagramSocke8、t(%%1);DatagramPacketip=newDatagramPacket(buf,buf.length);while(true){ds.receive(ip);}InetAddresstarget=InetAddress.getByName(%%2);DatagramSocketds=newDatagramSocket(%%3);Stringstr=%%4;byte[]buf=str.getBytes();Datag
7、dress>ips=ni.getInetAddresses();while(ips.hasMoreElements()){70(第页)System.out.println("IP:"+ips.nextElement().getHostAddress());}}}catch(Exceptione){e.printStackTrace();}*/4.端对端通信//importjava.net.*;byte[]buf=newbyte[1024];DatagramSocketds=newDatagramSocke
8、t(%%1);DatagramPacketip=newDatagramPacket(buf,buf.length);while(true){ds.receive(ip);}InetAddresstarget=InetAddress.getByName(%%2);DatagramSocketds=newDatagramSocket(%%3);Stringstr=%%4;byte[]buf=str.getBytes();Datag
此文档下载收益归作者所有