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();
}
}
}