java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java的Socket编写的多线程Server,支持并发访问

java Socket起步教程java使用Socket 编写一个Server
之前写过一个socket Server很基础,仅仅支持一次访问,立即会停止。真正的Server都支持大量的访问。大量并发访问,就属于多线程了。那么Server必须也启动多个线程来应对多个客户端。

要点:继承Thread线程类。

这样你就可以在浏览器里多次访问,并且可以多个人同时访问

package com.javaer.examples.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MutiUserServer extends Thread {
	private Socket client;

	public MutiUserServer(Socket c) {
		client = c;
	}

	 public void run() {

        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            int i = 0;
            String str = null;
            out.print("http/1.1 200 ok\r\n\r\n"); //浏览器协议
            while ((str = in.readLine())!=null) {
                System.out.println(String.valueOf(i) + ":" + str + " : " + str.length());
                i++;
                out.println("has receive...." + i);
                out.flush();
                if(str.length()==0){
                    System.out.println("break " + i);
                    break;
                }
                if (str.equals("end"))
                    break;
            }
            System.out.println("close " +i );
            client.close();
        } catch (Exception e) {
        }
    }

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("muti user server start");
		ServerSocket server=new ServerSocket(2156);
		while(true){
			MutiUserServer mus = new MutiUserServer(server.accept());
			mus.start();
		}
	}

}


This entry was posted in JAVA and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-muti-server-socket/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply