sserver.java
来自「JAVA Socket Server的响应处理.可用于SocketServer的」· Java 代码 · 共 92 行
JAVA
92 行
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 + =
减小字号Ctrl + -
显示快捷键?