`
zpball
  • 浏览: 924421 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

    博客分类:
  • J2EE
阅读更多
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();
		}*/
	}
}
分享到:
评论

相关推荐

    java写的远程控制

    Swing GUI编程、网络编程(TCP/IP、Socket)、多线程(因为同时处理输入和网络通信可能需要多个线程)、可能的加密技术(为了保证数据传输的安全)以及远程控制协议的设计与实现。对于想要学习Java远程控制软件开发...

    计网,网络编程实验(C,Java,Python).zip

    本实验包“计网,网络编程实验(C,Java,Python).zip”旨在深入探讨计算机网络原理,并通过三种主流编程语言——C、Java和Python——实践网络编程的基本概念和技术。 首先,我们要了解TCP(Transmission Control ...

    socket学习笔记

    本文将深入探讨“Socket学习笔记”中的核心知识点,主要通过分析提供的两个Java文件——SocketServer.java和SocketClient.java来阐述。 首先,Socket在计算机网络中扮演着客户端与服务器端通信的关键角色。它是一种...

    android socket编程源码—同一台PC的两个模拟器间的通信附详细文档

    在Android平台上,Socket编程是一种常见的网络通信方式,它允许设备之间通过TCP/IP协议进行数据交换。本项目聚焦于在同一台PC上运行的两个Android模拟器之间的Socket通信,这对于开发和测试分布式应用程序或需要设备...

    网络编程教程,绝对经典

    - **Socket编程**:Java中使用Socket类和ServerSocket类进行网络编程。 #### 十五、为什么要使用SocketAddress来管理网络地址 - **SocketAddress**:封装网络地址信息。 - **用途**:统一管理和操作网络地址。 ##...

Global site tag (gtag.js) - Google Analytics