zoukankan      html  css  js  c++  java
  • 网络编程——服务器端

    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;


    public class TestServer {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    //1、创建服务器监听器
    ServerSocket server = null;
    try {
    server = new ServerSocket(9527);
    //2、开始监听
    System.out.println("开始监听......");
    while(true){
    Socket socket = server.accept();//accept会进入阻塞状态,一旦有消息发送过来,就返回Socket对象
    //3、开启子线程进行消息处理
    new ProcessThread(socket);
    }
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally{
    if(server != null){
    try {
    server.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }



    }

    }

    public class ProcessThread extends Thread{
    private Socket socket;

    public ProcessThread(Socket socket){
    this.socket = socket;
    this.start();
    }

    @Override
    public void run() {
    // TODO Auto-generated method stub
    //3、从Socket的InputStream取数据
    BufferedReader br = null;
    try {
    br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String msg = br.readLine();
    System.out.println("接收的消息:" + msg);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally{
    if(br != null){
    try {
    br.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    if(socket != null){
    try {
    socket.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }

    }

    }

  • 相关阅读:
    poi 导出文件
    获取哪一年 周一的所有日期
    线程池配置
    mybatis基于唯一索引插入或更新
    mongoTemplate关联查询
    cas认证机制
    SpringBoot服务
    HashMap的底层实现
    maven仓库提示“Downloading: http://repo.maven.apache.org/maven2/”
    Tomcat安装SSL证书
  • 原文地址:https://www.cnblogs.com/fengshaolingyun/p/6785138.html
Copyright © 2011-2022 走看看