⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sserver.java

📁 JAVA Socket Server的响应处理.可用于SocketServer的处理
💻 JAVA
字号:

import java.net.*;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: lizh
 * Date: 2006-8-26
 * Time: 16:10:16
 * To change this template use File | Settings | File Templates.
 */
public class SServer {
  public final static int PORT = 11025;

  public static void main(String[] args) {
    SServer ss = new SServer();
    ss.execute();
  }

  public void execute() {
    ServerSocket sSocket = null;
    Socket socket = null;
    SServerTackle sServerTackle = null;
    int iCount = 0;
    try {
      sSocket = new ServerSocket(PORT);
      while (true) {
        socket = sSocket.accept();
        iCount++;
        sServerTackle = new SServerTackle();
        sServerTackle.setCountID(iCount);
        sServerTackle.setSocket(socket);
        sServerTackle.start();
      }
    }
    catch (Exception e) {
      System.out.println(e);
    }
    finally {
      try {
        if (sSocket != null) {
          sSocket.close();
        }
      }
      catch (Exception e) {
        System.out.println(e);
      }
    }
  }
}

class SServerTackle extends Thread {
  private Socket socket = null;
  private int countID = 0;

  public void setSocket(Socket socket) {
    this.socket = socket;
  }

  public void setCountID(int ID) {
    this.countID = ID;
  }

  public void run() {
    try {
      String strNo = "NO:" + countID+".";
      System.out.println(strNo);
      String strMsg = strNo + "Welcome.your IP is:";
      String strError = strNo + "Sorry,illegal input.";
      String strIn = "";
      InputStream is = socket.getInputStream();
      OutputStream os = socket.getOutputStream();
      strMsg += socket.getInetAddress().getHostAddress();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      strIn = br.readLine();
      if (strIn.equalsIgnoreCase("hello")) {
        os.write(strMsg.getBytes());
      }
      else {
        os.write(strError.getBytes());
      }
      os.flush();
      is.close();
      os.close();
      socket.close();
    }
    catch (Exception e) {
      System.out.println("NO:" + countID + "\n" + e);
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -