TCP模拟客户端和服务端小例

package com.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
/**
 * 客户端
 * @author Administrator
 *
 */
public class ClientTcp {

	public static void main(String[] args) {
		/**
		 * 模拟客户端,给tomcat发送请求(请记得把你的tomcat启动)
		 *1.创建socket
		 *2.设置连接和端口,端口号为tomcat的端口号8080
		 */
		
		
		Socket socket = null;
		try {
			socket = new Socket("127.0.0.1", 8080);
			PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
			InputStream inputStream = socket.getInputStream();
			byte[] bytes1 = new byte[1024];
			int count = 0;
			
			pw.println("GET / HTTP/1.1");
			pw.println("Host: localhost:8080");
			pw.println("Connection: keep-alive");
			pw.println("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			pw.println("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.1.2000 Chrome/30.0.1599.101 Safari/537.36");
			pw.println("DNT: 1");
			pw.println("Accept-Encoding: gzip,deflate");
			pw.println("Accept-Language: zh-CN");
			pw.println();//这个空行是结束标记
			
			//接收
			while((count = inputStream.read(bytes1)) != -1){
				String back = new String(bytes1, 0, count);
				System.out.println(back);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(socket != null){
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

  

package com.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * 服务端,模拟服务器
 * @author Administrator
 *
 */
public class ServerTcp {
	/**
	 * 1.创建服务
	 * 2.获取socket,输入流
	 * @param args
	 */
	public static void main(String[] args) {
		ServerSocket ss = null;
		try {
			//接收
			
			ss = new ServerSocket(10000);
			Socket socket = ss.accept();//阻滞式的
			//while循环是为了让服务器不停止
			while(true){
				
				InputStream is = socket.getInputStream();
				
				byte[] bytes = new byte[1024];
				int count = 0;
				//这个while循环,会卡住
				while((count = is.read(bytes)) != -1){
					String str = new String(bytes, 0, count);
					//这里仅打印浏览器发来的信息
					System.out.println(str);
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(ss != null){
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}

  

posted @ 2014-04-08 10:18  lxricecream  阅读(417)  评论(0)    收藏  举报