加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java网络编程入门SocketServer与Socket

发布时间:2020-12-14 23:53:11 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 URL 连接 :类URL代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

  1. URL 连接 :类URL代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。
  2. HttpURLConnection连接:相当于servlet,发送单个以post或get方式的请求,
  3. TCP/IP连接 可靠传输ServerSocket类 。 1).入门案例。 2).多线程阻塞式通讯。 阻塞式:比如recv某个socket的描述符,如果没有数据到,一直停在recv的状态,不释放socket资源,叫阻塞
  4. UDP连接 DatagramSocket 类, 此类表示用来发送和接收数据报包的套接字。
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,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();
    }

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

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,len));
        }
    }

}

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

}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读