//===========SMain.java
public class SMain {
public static void main(String[] args) {
new Thread(new SListener()).start();
}
}
//===========SListener.java
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SListener implements Runnable {
public SListener() {
}
public void run() {
BlockingQueue
50);
ExecutorService serverPool = new ThreadPoolExecutor(5, 50, 30,
TimeUnit.SECONDS, blockingQueue,
new ThreadPoolExecutor.DiscardPolicy());
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(7777);
serverSocket.setSoTimeout(30 * 60 * 1000);
} catch (IOException e) {
e.printStackTrace();
return;
}
while (true) {
try {
serverPool.execute(new Sprocessor(serverSocket.accept()));
} catch (InterruptedIOException iioe) {
continue;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//===========Sprocessor.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Sprocessor implements Runnable {
private final Socket socket;
public Sprocessor(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
System.out.println("接受到请求");
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String cmd;
while (true) {
cmd = in.readLine();
if (cmd.equals("quit")) {
break;
}
out.write(" " + cmd);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
} catch (Exception e) {
}
try {
if (out != null)
out.close();
} catch (Exception e) {
}
try {
if (socket != null)
socket.close();
} catch (Exception e) {
}
}
}
}
//=========python client
import socket
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.connect(('localhost',7777))
ss.send("aaa\n")
data = ss.recv(1024)
print data
ss.send("quit\n")
没有评论:
发表评论