java网络编程之TCP/IP ——SocketServer与Socket

java网络编程主要包含4部分: (注意设置超时时间)
1.URL 连接  :类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。
2.HttpURLConnection连接:相当于servlet,发送单个以post或get方式的请求,
3.TCP/IP连接   可靠传输ServerSocket类
4.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();
	}


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();
		}*/
	}
}

猜你喜欢

转载自zpball.iteye.com/blog/1623021