您的位置:首页 > 其它

使用自定义服务器、浏览器作为客户端访问

2012-03-26 23:47 363 查看
package com.hsj.net.login;

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

public class BSThread implements Runnable {

	private Socket s;
	public BSThread(Socket s) {
		this.s=s;
	}
	public void run() {		
		try {
			BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
			PrintWriter  out=new PrintWriter(s.getOutputStream(),true);
			String info=null;
			while((info=in.readLine())!=null){
				System.out.println(info);
				if(info.trim().length()<=0)
					break;
			}
			out.println("你好,欢迎免费使用我们的软件");
			s.close();
		} catch ( Exception e) {
			e.printStackTrace();
		}
	}

}
package com.hsj.net.login;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端:自定义
 * 客户端:浏览器,telent
 * @author heshengjun
 *
 */
public class BSDemo {

	public static void main(String[] args) throws Exception {
		ServerSocket ss=new ServerSocket(10010);
		while(true){
			Socket s=ss.accept();
			String ip=s.getInetAddress().getHostAddress();
			System.out.println("ip: "+ip);
			new Thread(new BSThread(s)).start();
		}
	}
}


这里有一个问题需要注意,对于浏览器发送过来的数据,最后面使用一个空行来区分消息头和正文。所以我们读取消息头的时候使用判断标志需要注意一下。不然会阻塞,程序停止运行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐