day24TCP并发上传。用户名进行校验。自己的图形化界面浏览器。URL。

/*
TCP并发上传。用户名进行校验。自己的图形化界面浏览器。URL。
*/



/*
需求:上传图片。
	()不就是复制图片吗?
1.服务端点。
2.读取客户端已有的图片数据
3.通过Socket输出流将数据发给服务端。
4读取服务端返回的信息。
5.关闭。

//单个复制问题请看day23的(复制文件代码)。

那么TCP并发上传图片?
为了让多个客户端同时并发访问服务端。
那么服务端最好就是将每个客户端封装到一个单独的线程中。
*/

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MoreCopy {

	/**多个客户端同时复制,就是上传
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}
class CopyThread implements Runnable
{
	private Socket s;
	CopyThread(Socket s)
	{
		this.s = s;
	}
	public void run()
	{
		String ip = s.getInetAddress().getHostAddress();
		
		try{
			int count = 1;
			System.out.println(ip+"...connet");
			BufferedInputStream bufin = new BufferedInputStream(
					s.getInputStream());
			File file = new File(ip+"("+count+").jpg");

			while(file.exists())//存在就创建。
				file = new File(ip+"("+(count++)+").jpg");

			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(file));
			
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = bufin.read(buf))!=-1){
				out.write(buf, 0, len);
				out.flush();
			}
			out.close();
			
			BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(
					s.getOutputStream()));
			bufout.write("复制成功!!!");
			bufout.flush();
			
			//PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
			//pw.println("复制成功!!!");
			
			System.out.println("server over");
			s.close();
			
		}
		catch(Exception e)
		{
			throw new RuntimeException(ip+"上传失败");
		}
	}
}

class CopySocket{
	public static void main(String[] args) throws Exception {
		Socket s = new Socket("127.0.0.1",10007);
		if(args.length!=1)//传值
		{
			System.out.println("请输入正确的文件");
			return ;
		}
		File file = new File(args[0]);
		
		if(!file.getName().endsWith(".jpg"))
		{
			System.out.println("请选择正确的文件名");
			return;
		}
		
		if(file.length()>=1024*1024*5)
		{
			System.out.println("请选择文件是否是图像");
			return;
		}
		
		if(!(file.exists() || file.isFile()))
			{
				System.out.println("文件不存在");
				return;
			}
		
		BufferedInputStream in = new BufferedInputStream(
				new FileInputStream(file));
		BufferedOutputStream bufout = new BufferedOutputStream(
				s.getOutputStream());
		
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = in.read(buf))!=-1){
			bufout.write(buf, 0, len);
			bufout.flush();
		}
		s.shutdownOutput();//结束标记
		
		/*BufferedReader bufin = new BufferedReader(new InputStreamReader(
				s.getInputStream()));
			String line = bufin.readLine();*/
		BufferedInputStream bufin = new BufferedInputStream(
				s.getInputStream());
		byte[] buf1 = new byte[1024];
		int len1 = bufin.read(buf1);
		String line = new String(buf1,0,len1);
		System.out.println(line+"over");
		in.close();
		s.close();
	}
}
class CopyServerSocket{
	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(10007);
		while(true)
		{
			Socket s = ss.accept();//阻塞式方法
			new Thread(new CopyThread(s)).start();
		}		
	}
}

/*
客户端通过键盘录入用户名
服务器对这个用户名进行校验

如果该用户存在,在服务端显示XXX已登陆。
并在客户端显示XXX欢迎光临

如果该用户不存在,在服务端显示XXX尝试登陆
并在客户端显示XXX,该用户不存在。

最多登录三次。
*/
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class LoginDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}
class LoginSocket{
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
	
		Socket s = new Socket("127.0.0.1",10005);
		BufferedReader bufr = new BufferedReader(
				new InputStreamReader(System.in));
		OutputStream os = s.getOutputStream();
		InputStream is = s.getInputStream();
		String line = null;
		byte[] buf = new byte[1024];
		for(int x=0;x<3;x++)
		{
			line = bufr.readLine();
			if(line==null)//按ctrl+c=-1,null
				break;
			os.write(line.getBytes());
			int len = is.read(buf);
			String info = new String(buf,0,len);
			System.out.println("ServerSocket:"+info);
			if(info.contains("欢迎"));
				break;
		}
		bufr.close();
		s.close();
	}
}
class LoginThread implements Runnable{
	private Socket s;
	LoginThread(Socket s){
		this.s = s;
	}
	public void run(){
		byte[] buf = new byte[1024];
		int len = 0;
		OutputStream os= null;
		try {
			InputStream is = s.getInputStream();
			 os = s.getOutputStream();
			BufferedReader bufr = new BufferedReader(new InputStreamReader(
					new FileInputStream("user.txt")));//数据库有的用户名。
			String line = null;
			for(int x=0;x<3;x++){
				len = is.read(buf);
				String info = new String(buf,0,len);
				if(info==null)
					break;
				
				boolean flag = false;
				while((line =bufr.readLine())!=null){
					if(line.equals(info)){
						flag = true;
						break;
					}
				}
				if(flag){
					os.write((line+"欢迎,登陆成功").getBytes());
					System.out.println(line+"已登陆");
					//s.shutdownOutput();l
					break;
				}
				else{
					os.write((info+"登陆失败").getBytes());
					System.out.println(info+"尝试登陆");
				}
				s.close();
			}
			//bufr.close();
			//s.close();
		} catch (IOException e) {
			throw new RuntimeException("错误信息");
		}
	}
}
class LoginServer{
	public static void main(String[] args) throws Exception{
		ServerSocket ss = new ServerSocket(10005);
		while(true){
			Socket s = ss.accept();
			new Thread(new LoginThread(s)).start();
		}
	}
}

/*
1.
客户端:浏览器
服务端:自定义服务端,让浏览器访问。代码如下:
在浏览器上输入:http://127.0.0.1:11000,输入前要开启服务端
dos命令行:远程登陆工具:telnet 127.0.0.1 11000
*/
import java.io.*;
import java.net.*;

class ServerDemo 
{
	public static void main(String[] args) throws Exception
	{
		ServerSocket ss = new ServerSocket(11000);

		Socket s = ss.accept();
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);

		System.out.println(s.getInetAddress().getHostAddress()+")connet...");

		out.println("客户端你好");
		
		//看看客户端给服务器发了什么信息,用浏览器。
		InputStream is = s.getInputStream();
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		system.out.println(new String(buf,0,len));
		
		s.close();
		ss.close();
	}
}
/*
客户端:浏览器
服务端:Tomcat服务器
访问本机的tomcat:127.0.0.1:8080.

Tomcat建立一个自己的网站:
webapps文件夹里我们建立一个文件夹:myweb
myweb里面建立一个demo.html文件。里面有html代码。
然后在浏览器里输入:127.0.0.1:8080/myweb/demo.html.
*/

/*
//看看客户端给服务器发了什么信息,用浏览器。
		InputStream is = s.getInputStream();
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		system.out.println(new String(buf,0,len));

	我们看到服务器的一个消息头:http://127.0.0.1 11000/myweb/demo.html

		GET /myweb/demo.html HTTP/1.1.
		Accept:image/gif........	//接收文件
		Accept-Language:zh-cn		//语言
		Accept-Encoding:gzip,deflate	//压缩格式,省流量,速度快。  
		User-Agent:.....
		Host:127.0.0.1:11000
		Connection:Keep-Alive  //存活
		空行
		///这里有请求数据体



		那我们也搞一个客户端,向Tomcat服务器发这个。
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyIEDemo {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Socket s = new Socket("127.0.0.1",8080);//Tomcat服务器端口
		PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
		
		pw.println("GET /myweb/demo.html HTTP/1.1");
		pw.println("*/*");
		pw.println("Accept-Language:zh-cn");
		pw.println("Host:127.0.0.1:11000");
		pw.println("Connection:Keep-Closed");//Keep-Alive会比较慢,保持连接
		
		
		pw.println("");//一定要有空行,固定格式
		pw.println("");
		
		//我们读回来服务器发送过来的数据。
		BufferedReader bufr = new BufferedReader(
				new InputStreamReader(s.getInputStream()));
		String line = null;
		while((line = bufr.readLine())!=null)
		{
			System.out.println(line);
		}
		s.close();
	}
}

import java.awt.Button;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
//自己的图形化界面浏览器
class MyIEByGUI{
	public static void main(String[] args){
		new MyIEGUI();
	}
}

class MyIEGUI
{
	private Frame f;
	private Button b;
	private TextField tf;
	private TextArea ta;
	
	private Dialog dia;
	private Label lab;
	private Button okbut;
	MyIEGUI()
	{
		init();
	}
	public void init()
	{
		f = new Frame("my frame");
		b = new Button("点击转到");
		tf = new TextField(50);
		ta = new TextArea(30,60);
		
		dia = new Dialog(f,true);
		dia.setBounds(300,200, 300, 250);
		dia.setLayout(new FlowLayout());
		lab = new Label();
		okbut = new Button("确定");
		dia.add(lab);
		dia.add(okbut);
		
		f.setBounds(200, 200, 550, 550);
		f.setLayout(new FlowLayout());
		f.add(tf);f.add(b);f.add(ta);
		myEvent();
		f.setVisible(true);
	}
	private void myEvent() {
		tf.addKeyListener(new KeyAdapter()
		{
			public void keyPressed(KeyEvent e)
			{
				if(e.getKeyCode()==KeyEvent.VK_ENTER)
				{
					show();
				}
			}
		});
		dia.addWindowListener(
				new WindowAdapter()
				{
					public void windowClosing(WindowEvent e)
					{
						dia.setVisible(false);
					}
				});
		
		f.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				System.exit(0);
			}
		});
		
		b.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e) {
				show();
			}
		});
	}
	private void show()
	{
		String url = tf.getText();//http://127.0.0.1:11000/myweb/demo.html
		int index  = url.indexOf("//")+2;
		 int index1 = url.indexOf("/",index);
		 int num = url.lastIndexOf(":");
		 String Host = url.substring(index, num);
		 String port1 = url.substring(num+1, index1);
		 int port = Integer.parseInt(port1);
		 String path = url.substring(index1);
		 
		 try{
		 		Socket s = new Socket(Host,port);//Tomcat服务器端口8080
		 		PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
		
		 		/*这是向8080发送的数据
		 		pw.println("GET /+"+path+" HTTP/1.1");
		 		pw.println("**");//
		 		pw.println("Accept-Language:zh-cn");
		 		pw.println("Host:127.0.0.1:11000");
		 		pw.println("Connection:Keep-Closed");//Keep-Alive会比较慢,保持连接
		 		
		 		
		 		pw.println("");//一定要有空行,固定格式
		 		pw.println("");
		 		*/
		 		//我们读回来服务器发送过来的数据。
		 		BufferedReader bufr = new BufferedReader(
		 				new InputStreamReader(s.getInputStream()));
		 		String line = null;
		 		while((line = bufr.readLine())!=null)
		 		{
		 			ta.append(line+"\r\n");//这里要重置
		 		}
		 		s.close();
		 }catch(Exception e){
			 
		 }
	}
}
/*
下面我面要把网页上显示出来的消息头给去掉,
并且使用url对象。
因为URL比较复杂,我们就先去找这个对象。
假如没有这个对象,那么我们也要自己造一个。

URL里面有一堆方法可以获取
String getProtocol():获取协议名称。
String getHost():获取主机名称
String getFile():获取文件名
String getPath():获取路径
String getQuery():获取查询部
int getPort():获取端口号//没指定端口,为-1,上网时,默认为80。
*/
import java.net.URL;
public class URLDemo {
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		URL url = new URL("http://127.0.0.1:8080/myweb/demo.html");
		
		System.out.println(url.getFile());//文件/myweb/demo.html
		System.out.println(url.getPath());//路径/myweb/demo.html
		System.out.println(url.getHost());//主机名127.0.0.1
		System.out.println(url.getProtocol());//http,协议。
		System.out.println(url.getQuery());//这个是后面的用户信息null
		System.out.println(url.getPort());//端口8080
	}
}

/*
:
= URL对象.openConnection()//返回一个URLConnection对象
它也封装了Socket的InputStream方法,是没有响应消息头的。
*/
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionDemo {
	public static void main(String[] args) throws Exception{
		URL url = new URL("http://127.0.0.1:8080/myweb/demo.html");
		URLConnection conn = url.openConnection();//返回带着协议封装的Socket
		System.out.println(conn);
		//sun.net.www.protocol.http.HttpURLConnection:http://127.0.0.1:8080/myweb/demo.html
		
		InputStream  is = conn.getInputStream();
		byte[] buf = new byte[1024];
		int len = is.read(buf);
		System.out.println(new String(buf,0,len));//不带消息头的返回信息,
		//这个对象可以不用关。
	}
}

/*
没有消息头代码的MyIEByGUI2.代码

修改MyIEByGUI.java代码,里面的Show方法。
*/
		private void show()
		{
			ta.setText("");
			try{
					 String urlText = tf.getText();//http://127.0.0.1:11000/myweb/demo.html
					URL url = new URL(urlText);
					URLConnection conn  = url.openConnection();
					BufferedReader bufr = new BufferedReader(
							new InputStreamReader(conn.getInputStream()));
					String line = null;
					while((line = bufr.readLine())!=null)
					{
						ta.append(line+"\r\n");
					}
					s.close();
			 }catch(Exception e){
				 
			 }
		}

/*小知识点:
Socket(),空构造函数,创建后可以用connect()连接。
ServerSocket(int port,int backlog).其中backlog是最大连接数,
因为一台机器的性能是有限的,所以可以设定一个连接数。
*/
/*
域名解析:www.sina.cn想要将主机名变成IP地址,
需要域名解析。DNS。

浏览器在去公网DNS服务器之前,会先找本机的域名解析。在文件夹里。
c:\WINDOWS\system32\drivers\etc\hosts文件里。

拿新浪的IP地址,InetAddress.getByName("www.sina.com.cn");
应用一:自己配置好新浪的IP,上网可能会快上一点。
方法:修改本地的hosts文件。这样就不走域名解析了。
拿到的IP地址    www.sina.com  

应用二:防止更新。把更新要访问的网站的IP配成本地。
网站屏幕:把想屏幕网站名的IP配成本地。
如:127.0.0.1    <a target=_blank href="http://www.myeclipse.com*/">www.myeclipse.com


*/


</a>图片:域名解析...











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值