方案名称:服务器虚拟化解决方案
方案地址:http://www.zrway.com/solutions/virtualization/server/
服务器监听端口 做个无限循环 接到一个连接就创建一个通道线程,并将通道线程存储到一个list集合中import java.io.BufferedReaderimport java.io.IOExceptionimport java.io.InputStreamReaderimport java.io.PrintWriterimport java.net.ServerSocketimport java.net.Socketimport java.text.SimpleDateFormatimport java.util.ArrayListimport java.util.Dateimport java.util.List/* * 4.用socket通讯写出多个客户端和一个服务器端的通讯, * 要求客户发送数据后能够回显相同的数据(回显功能)(实用TCP方式)。 */public class Test4Server { // 主入口public static void main(String[] args) throws IOException {scoketServer() } // 开启的tcp8888监听端口public static void scoketServer() throws IOException {ServerSocket server = new ServerSocket(8888) while (true) {// 未连通前线程阻塞,连通后开启一个socket通道线程后继续监听8888端口Socket socket = server.accept() System.out.println(socket.getInetAddress().getHostAddress()+ "连接进入") new SocketThread(socket).start() }} } // 一个服务器端口中监听多个客服端通道线程class SocketThread extends Thread {// 所有通道写入流的集合private static List<PrintWriter>list =new ArrayList<PrintWriter>()private BufferedReader bufferedReader private PrintWriter printWriterpublic SocketThread(Socket socket) throws IOException {this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())) this.printWriter = new PrintWriter(socket.getOutputStream()) list.add(printWriter) } @Overridepublic void run() {String string = null while (true) {try {// 服务器在通道中读到的信息回显给客服端string = bufferedReader.readLine() System.out.println("客服端信息:" + string) for(PrintWriter printWriter:list ){printWriter.write("服务器回显:" + string + "\r\n") printWriter.flush() }} catch (IOException e) { }} }}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)