java网络编程主要包含4部分: (注意设置超时时间)
- URL 连接 :类URL代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。
- HttpURLConnection连接:相当于servlet,发送单个以post或get方式的请求,
- TCP/IP连接 可靠传输ServerSocket类 。 1).入门案例。 2).多线程阻塞式通讯。 阻塞式:比如recv某个socket的描述符,如果没有数据到,一直停在recv的状态,不释放socket资源,叫阻塞
- UDP连接 DatagramSocket 类, 此类表示用来发送和接收数据报包的套接字。
TCP/IP 连接 Server服务器端
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; /** [email protected]:Server [email protected]: chenyoulong [email protected] :2012-7-30 上午10:35:09 [email protected]:TODO */ public class SendServer { /** * @throws IOException * @Title: main * @Description: TODO * @param @param args * @return void * @throws */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocket server=new ServerSocket(8888); System.out.println("server start"); Socket sock=server.accept(); sock.setSoTimeout(6000); //服务器端设置连接超时时间,该操作只对读取(read)操作有效。 //读取 //字节流的形式读取 // 优缺点分析,弱点:受byte[]大小的限制 ,优点:不受回车符(/r)和换行符(/n)限制 InputStream input=sock.getInputStream(); byte[] buf =new byte[1024]; System.out.println("InputStream==="+input); if(input!=null){ int len=input.read(buf); ToolKit.writeLog(SendServer.class.getName(), "服务器端收到的报文:/n"+new String(buf, 0, len)); } /* //字符流的形式读取 //(遇到换行符或者回车符就终止,还是谨慎使用) BufferedReader read=new BufferedReader(new InputStreamReader(sock.getInputStream())); String readStr=null; if((readStr=read.readLine())!=null){ ToolKit.writeLog(Server.class.getName(), "服务器端收到的报文:/n"+readStr); } if(read!=null) read.close(); */ /*//输出 String outStr="我是server服务器端"; BufferedWriter write=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); if(outStr!=null){ write.write(outStr); } if(write!=null) write.close();*/ //挂关闭资源 if(sock!=null) sock.close(); if(server!=null) server.close(); }
TCP/IP连接 Client客户端
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import org.apache.log4j.Logger; /** [email protected]:ReceiveClient [email protected]: chenyoulong [email protected] :2012-8-3 下午2:17:26 [email protected]:TODO */ public class ReceiveClient { private final String IP=Setting.RECEIVE_IP; private final int PORT=Setting.RECEIVE_PORT; private Logger log = Logger.getLogger(Sender.class.getName()); //发送 /** * @throws Exception * 发送报文 * @Title: send * @Description: TODO * @param @param reqMessage * @return void * @throws */ public void send(String reqMessage) throws Exception{ Socket sock=null; BufferedOutputStream out=null; try { sock=new Socket(); SocketAddress sockAdd=new InetSocketAddress(IP, PORT); sock.connect(sockAdd, 2000); //客户端设置连接建立超时时间 out=new BufferedOutputStream(sock.getOutputStream()); out.write(reqMessage.getBytes()); out.flush(); } catch (UnknownHostException e) { // TODO Auto-generated catch block log.error("网络连接异常"+Strings.getStackTrace(e)); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block log.error("网络连接异常/n"+Strings.getStackTrace(e)); e.printStackTrace(); }finally{ if(out!=null){ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(sock!=null){ try { sock.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //接收 public String reiceve() throws Exception{ Socket sock=null; BufferedInputStream in=null; try { sock=new Socket(IP,PORT); in = new BufferedInputStream(sock.getInputStream()); if ((sock == null) || (in == null)) { throw new Exception("套接口无效,无法读取数据"); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte[] bts = new byte[10000]; int totalLen = 0, len = 0; while ((len = in.read(bts, totalLen, 1000)) != -1) { totalLen += len; } String result = new String(bts); //注意字符编码 return result.trim(); } //main函数示例 public static void main(String[] args){ //发送报文 //发送 String str="我是客户端!" try { new ReceiveClient().send(str); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //接收报文 /*try { String recStr=new Receiver().reiceve(); System.out.println("客户端接收到的结果=="+recStr); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } }
TCP/IP连接多线程阻塞式服务端1——实现runnable接口
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; /** [email protected]:ThreadSocket [email protected]: chenyoulong [email protected] :2012-8-1 上午10:00:41 [email protected]:TODO */ public class ThreadSocket implements Runnable { private Socket sock; public ThreadSocket(Socket sock){ this.sock=sock; } /* * <p>Title: run</p> * <p>Description: </p> * @see java.lang.Runnable#run() */ public void run() { // TODO Auto-generated method stub InputStream input=null; try { input = sock.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* //字符流的形式读取(遇到换行符或者回车符就终止,还是谨慎使用) BufferedReader read=new BufferedReader(new InputStreamReader(input)); String readStr=null; try { if((readStr=read.readLine())!=null){ System.out.println("服务器端收到的报文:/n"+readStr); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(read!=null) { try { read.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ //字节流 byte[] buf = new byte[1024]; if (input != null) { int len=0; try { len = input.read(buf); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("服务器端收到的报文:/n"+ new String(buf, 0, len)); } } }
TCP/IP连接多线程阻塞式服务端2——main函数
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** [email protected]:OnRunSendServer [email protected]: chenyoulong [email protected] :2012-8-1 上午10:06:28 [email protected]:TODO */ public class OnRunSendServer { /** * @throws IOException * @Title: main * @Description: TODO * @param @param args * @return void * @throws */ public static void main(String[] args) { // TODO Auto-generated method stub ServerSocket server = null; try { server = new ServerSocket(8888); System.out.println("send服务器start!"); Socket sock = null; while (true) { sock = server.accept(); sock.setSoTimeout(12000);//设置读取连接超时时间 ThreadSocket tsock = new ThreadSocket(sock); new Thread(tsock).start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }/*finally{ //这里还是不要finally关闭ServerSocket为好,防止某个socket连接超时导致整个ServerSocket都关闭了。 try { server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ } }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10849.html