Java網絡編程入門SocketServer與Socket
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;/* @ClassName:Server @author: chenyoulong @date :2012-7-30 上午10:35:09 @Description: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(); }</pre>
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;/ @ClassName:ReceiveClient @author: chenyoulong
@date :2012-8-3 下午2:17:26 @Description: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(); }*/ }
}</pre>
TCP/IP連接多線程阻塞式服務端1——實現runnable接口
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket;/* @ClassName:ThreadSocket @author: chenyoulong @date :2012-8-1 上午10:00:41 @Description: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)); } }
}</pre>
TCP/IP連接多線程阻塞式服務端2——main函數
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;/* @ClassName:OnRunSendServer @author: chenyoulong @date :2012-8-1 上午10:06:28 @Description: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(); } }*/ }
}</pre>