JAVA SOCKET编程单线程简单实例
服务端:
package socketProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import util.*;
import util.screenShot;
public class newServer {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
ServerSocket serverSocket = new ServerSocket(20000);
Socket socket = new Socket();
socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
String info = in.readLine();
out.println("has receive...");
out.flush();
if(info.equals("截图")){
//调用截图方法
}else if(info.equals("进程")){
//调用获取进程号方法
}else if(info.equals("关机")){
//调用关机方法
}
if(info.equals("end")){
break;
}
}
System.out.println("已跳出循环,接下来是关闭流");
in.close();
out.close();
socket.close();
serverSocket.close();
}
}
************************************************************************************************
客户端:
package socketProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class newClient {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
Socket socket = new Socket("127.0.0.1",20000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
while(true){
String info = wt.readLine();
out.println(info);
out.flush();
if(info.equals("end")){
break;
}
System.out.println(in.readLine());
}
wt.close();
out.close();
in.close();
socket.close();
}
}