黑马程序员_Java基础_网络编程相关小项目
2014-12-14 11:44
676 查看
一、网络编程(TCP-上传图片)
[java] view
plaincopy
/*
需求:上传图片。
*/
/*
客户端:
1.服务端点。
2.读取客户端已有的图片数据。
3.通过socket输出流将数据发给服务端。
4.读取服务端反馈信息。
5.关闭。
*/
import java.net.*;
import java.io.*;
class PicClient
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("172.16.56.237",1005);
FileInputStream fis=new FileInputStream("e:\\1.jpg");
OutputStream out=s.getOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1)
{
out.write(buf,0,len);
}
s.shutdownOutput();//告诉服务端数据已写完。(增加结束标记)
InputStream in=s.getInputStream();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
[java] view
plaincopy
/*
服务端:
*/
import java.net.*;
import java.io.*;
class PicServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
Socket s=ss.accept();
InputStream in=s.getInputStream();
FileOutputStream fos=new FileOutputStream("f:\\server.jpg");
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1)
{
fos.write(buf,0,len);
}
OutputStream out=s.getOutputStream();
out.write("图片已收到".getBytes());
fos.close();
s.close();
ss.close();
}
}
二、网络编程(TCP-客户端并发上传图片)
[java] view
plaincopy
/*
需求:上传图片。
*/
/*
客户端:
1.服务端点。
2.读取客户端已有的图片数据。
3.通过socket输出流将数据发给服务端。
4.读取服务端反馈信息。
5.关闭。
*/
import java.net.*;
import java.io.*;
class PicClient
{
public static void main(String[] args)throws Exception
{
if(args.length!=1)
{
System.out.println("请选择一个jpg格式的图片。");
return;
}
File file=new File(args[0]);
if(!(file.exists()&&file.isFile()))
{
System.out.println("该文件有问题,要么存在,要么不是文件");
return;
}
if(!file.getName().endsWith(".jpg"))
{
System.out.println("图片格式错误,请重新选择");
return;
}
if(file.length()>1024*1024*5)
{
System.out.println("文件过大,禁止上传!");
return;
}
Socket s=new Socket("172.16.56.237",1005);
FileInputStream fis=new FileInputStream(file);
OutputStream out=s.getOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1)
{
out.write(buf,0,len);
}
s.shutdownOutput();//告诉服务端数据已写完。(增加结束标记)
InputStream in=s.getInputStream();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
[java] view
plaincopy
/*
服务端:
当A客户端连接上后,被服务端获取到后,服务端就在执行具体流程。这时B客户端连接的话,只能等待。
因为服务端还没有处理完A客户端的请求,还没有循环结束回来执行下一次accept方法,所以暂时获取不到
B客户端对象。
所以,为了可以让多个客户端同时并发访问服务端,那么服务端最好就是将每个客户端封装到一个
单独的线程中,这样就可以同时处理多个客户端请求。
如何定义线程呢?
只要明确了每一个客户端要在服务端执行的代码即可,将该代码存入run方法中。
*/
import java.net.*;
import java.io.*;
class PicThread implements Runnable
{
private Socket s;
PicThread(Socket s)
{
this.s=s;
}
public void run()
{
int count=1;
String ip=s.getInetAddress().getHostAddress();
try
{
System.out.println(ip+"..........connceted");
InputStream in=s.getInputStream();
//为了不覆盖
File file=new File("f:\\"+ip+"("+(count)+")"+".jpg");
while(file.exists())
file=new File("f:\\"+ip+"("+(count++)+")"+".jpg");
FileOutputStream fos=new FileOutputStream(file);
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1)
{
fos.write(buf,0,len);
}
OutputStream out=s.getOutputStream();
out.write("图片已收到".getBytes());
fos.close();
s.close();
}
catch (Exception e)
{
throw new RuntimeException(ip+"上传失败!");
}
}
}
class PicServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
while(true)
{
Socket s=ss.accept();
new Thread(new PicThread(s)).start();
}
}
}
三、网络编程(TCP-客户端并发登录)
[java] view
plaincopy
/*
客户端通过键盘录入用户名,服务端对这个用户名进行校验。
如果该用户存在,在服务端显示xxx,已登录,并在客户端显示xxx,欢迎登录。
如果该用户存在,在服务端显示xxx,尝试登录。并在客户端显示xxx,该用户不存在。
最多登录3次。
*/
import java.io.*;
import java.net.*;
class LoginClient
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("172.16.56.237",1005);
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
for(int i=0;i<3;i++)
{
String line=bufr.readLine();
if(line==null)
break;
out.println(line);
String info=bufIn.readLine();
System.out.println("info:"+info);
if(info.contains("欢迎"))
break;
}
bufr.close();
s.close();
}
}
[java] view
plaincopy
/*
服务端
*/
import java.io.*;
import java.net.*;
class UserThread implements Runnable
{
private Socket s;
UserThread(Socket s)
{
this.s=s;
}
public void run()
{
String ip=s.getInetAddress().getHostAddress();
try
{
for(int i=0;i<3;i++)
{
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String name=bufIn.readLine();
if(name==null)
return;
BufferedReader bufr=new BufferedReader(new FileReader("e:\\user.txt"));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
String line=null;
boolean flag=false;
while((line=bufr.readLine())!=null)
{
if(line.equals(name))
{
flag=true;
break;
}
}
if(flag)
{
System.out.println(name+",已登录");
out.println(name+",欢迎光临。");
}
else
{
System.out.println(name+",尝试登录。");
out.println(name+",用户名不存在。");
}
}
s.close();
}
catch (Exception e)
{
throw new RuntimeException(ip+"校验失败");
}
}
}
class LoginServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
while(true)
{
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
四、网络编程(浏览器客户端-自定义服务端)
[java] view
plaincopy
/*
演示客户端和服务端。
1.
客户端:浏览器
服务端:自定义
*/
import java.net.*;
import java.io.*;
class ServerDemo
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("客户端你好");//输出HTML文本
s.close();
ss.close();
}
}
五、网络编程(浏览器客户端-Tomcat服务端)
1.下载好Tomcat服务端,解压到任意路径。
2.进入Tomcat文件夹的bin目录下,点击startup.bat文件,启动Tomcat服务器。
可以看到配置信息里面的服务器端口:8080
3.进入浏览器输入: http://172.16.56.237:8080/ 打开了Tomcat网页。
这样的话,自己写个HMTL:
[html] view
plaincopy
<html>
<body>
<h1>
这是我的第一个网页
<h1>
<font size=5 color=red>欢迎光临</font>
<div>
1234567890</br>
3456789090</br>
5678987654</br>
</div>
</body>
</html>
保存成index.html文件。然后在Tomcat文件夹的webapps下建立一个myweb文件夹,将index.html放入。
在浏览器中指定具体服务器要打开html文件的路径:
http://172.16.56.237:8080//myweb/index.html
六、网络编程(自定义浏览器-Tomcat服务端)
[java] view
plaincopy
/*
客户端:浏览器
服务端:Tomcat服务器
*/
import java.net.*;
import java.io.*;
class ServerDemo
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
System.out.println(new String(buf,0,len));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("<font color='red' sixe'10'>客户端你好</font>");//输出HTML文本
s.close();
ss.close();
}
}
运行自定义服务器后,在浏览器输入地址:http://172.16.56.237:1005/
172.16.56.237
GET / HTTP/1.1
Host: 172.16.56.237:1005
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like G
ecko) Chrome/21.0.1180.83 Safari/537.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3
这些都是浏览器向服务器发送请求的信息。包含浏览器的信息。
[java] view
plaincopy
/*模仿IE浏览器从Tomcat服务器读取index.html
*/
import java.io.*;
import java.net.*;
class MyIE
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("172.16.56.237",8080);
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("GET /myweb/index.html HTTP/1.1");//浏览器请求的文件目录
out.println("Accept: */*");//浏览器支持的文件 */* 支持所有
out.println("Accept-Language: zh-CN");//浏览器支持的语言
out.println("Host: 172.16.56.237:1005");//浏览器请求的地址
out.println("Connection: closed");//连接状态 closed 数据发送完毕,结束
out.println();
out.println();
BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null)
{
System.out.println(line);
}
s.close();
}
}
七、网络编程(自定义图形界面浏览器-Tomcat服务端)
[java] view
plaincopy
/*
自定义图形界面浏览器-Tomcat服务端:
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class MyIEByGUI
{
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okBut;
MyIEByGUI()
{
init();
}
public void init()
{
f=new Frame("my window");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf=new TextField(60);
but=new Button("转到");
ta=new TextArea(25 ,70);// 行,列
d=new Dialog(f,"提示信息",true);//第3个参数:指定在显示的时候是否阻止用户将内容输入到其他顶级窗口中。
d.setBounds(400,200,240,150);
d.setLayout(new FlowLayout());
lab=new Label();
okBut=new Button("确定");
d.add(lab);
d.add(okBut);
f.add(tf);
f.add(but);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
try
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
okBut.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
d.setVisible(false);
}
});
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
}
private void showDir()throws Exception
{
ta.setText("");//清空
String url=tf.getText();// http://172.16.56.237:8080/myweb/index.html
int index1=url.indexOf("//")+2;
int index2=url.indexOf("/",index1);
String str=url.substring(index1,index2);
String[] arr=str.split(":");
String host=arr[0];
int port=Integer.parseInt(arr[1]);
String path=url.substring(index2);
//ta.setText(str+"..."+path);//测试
Socket s=new Socket(host,port);
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("GET "+path+" HTTP/1.1");//浏览器请求的文件目录
out.println("Accept: */*");//浏览器支持的文件 */* 支持所有
out.println("Accept-Language: zh-CN");//浏览器支持的语言
out.println("Host: 172.16.56.237:1005");//浏览器请求的地址
out.println("Connection: closed");//连接状态 closed 数据发送完毕,结束
out.println();
out.println();
BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}
s.close();
}
public static void main(String[] args)
{
new MyIEByGUI();
}
}
八、网络编程(URL-URLConnection)
[java] view
plaincopy
/*
String getFile()
获取此 URL 的文件名。
String getHost()
获取此 URL 的主机名(如果适用)。
String getPath()
获取此 URL 的路径部分。
int getPort()
获取此 URL 的端口号。
String getProtocol()
获取此 URL 的协议名称。
String getQuery()
获取此 URL 的查询部分。
*/
import java.net.*;
import java.io.*;
class URLDemo
{
public static void main(String[] args)throws MalformedURLException
{
URL url=new URL("http://172.16.56.237/myweb/index.html?name=yangcheng&age=21");
System.out.println("getProtocol:"+url.getProtocol());
System.out.println("getHost:"+url.getHost());
System.out.println("getPort:"+url.getPort());
System.out.println("getPath:"+url.getPath());
System.out.println("getFile:"+url.getFile());
System.out.println("getQuery:"+url.getQuery());
/*
int port=getPort();
if(port==-1)
port=80;
*/
}
}
[java] view
plaincopy
/*
URLConnection:
*/
import java.net.*;
import java.io.*;
class URLConnectionDemo
{
public static void main(String[] args)throws Exception
{
URL url=new URL("http://172.16.56.237:8080/myweb/index.html");
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
System.out.println(new String(buf,0,len));
}
}
既然如此,那么:
[java] view
plaincopy
/*
通过URLConnection拆封:
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class MyIEByGUI2
{
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okBut;
MyIEByGUI2()
{
init();
}
public void init()
{
f=new Frame("my window");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf=new TextField(60);
but=new Button("转到");
ta=new TextArea(25 ,70);// 行,列
d=new Dialog(f,"提示信息",true);//第3个参数:指定在显示的时候是否阻止用户将内容输入到其他顶级窗口中。
d.setBounds(400,200,240,150);
d.setLayout(new FlowLayout());
lab=new Label();
okBut=new Button("确定");
d.add(lab);
d.add(okBut);
f.add(tf);
f.add(but);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
try
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
okBut.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
d.setVisible(false);
}
});
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
}
private void showDir()throws Exception
{
ta.setText("");//清空
String urlPath=tf.getText();// http://172.16.56.237:8080/myweb/index.html
URL url=new URL(urlPath);
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
ta.setText(new String(buf,0,len));
}
public static void main(String[] args)
{
new MyIEByGUI2();
}
}
九、网络编程(小知识点)
Socket类:
Socket() :通过系统默认类型的 SocketImpl 创建未连接套接字
void connect(SocketAddress endpoint) :将此套接字连接到服务器。
InetSocketAddress类:
而:InetSocketAddress继承自SocketAddress
InetSocketAddress类实现 IP 套接字地址(IP 地址 + 端口号)。它还可以是一个对(主机名 + 端口号),在此情况下,将尝试解析主机名。如果解析失败,则该地址将被视为未解析 地址,但是其在某些情形下仍然可以使用,比如通过代理连接。
而InetAddress类实现 IP地址。
ServerSocket类:
public ServerSocket(int port,int backlog)throws IOException
利用指定的 backlog 创建服务器套接字并将其绑定到指定的本地端口号。
端口号 0 在所有空闲端口上创建套接字。
port - 指定的端口;或者为 0,表示使用任何空闲端口。
backlog - 队列的最大长度。也就是联机数。
十、网络编程(域名解析)
例如:
要访问www.baidu.com
先查看本地的hosts文件(域名和对应的IP缓存)有没有www.baidu.com的IP。有的话,直接到hosts文件www.baidu.com对应的IP地址去访问。如果没有则会去DNS服务器找www.baidu.com的对应IP。
hosts文件最常用来屏蔽危险连接。例如将不安全的域名直接在hosts文件中和127.0.0.1回环地址绑定。这个危险的网站就不会去DNS服务器找IP了,网站也就无法打开。
[java] view
plaincopy
/*
需求:上传图片。
*/
/*
客户端:
1.服务端点。
2.读取客户端已有的图片数据。
3.通过socket输出流将数据发给服务端。
4.读取服务端反馈信息。
5.关闭。
*/
import java.net.*;
import java.io.*;
class PicClient
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("172.16.56.237",1005);
FileInputStream fis=new FileInputStream("e:\\1.jpg");
OutputStream out=s.getOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1)
{
out.write(buf,0,len);
}
s.shutdownOutput();//告诉服务端数据已写完。(增加结束标记)
InputStream in=s.getInputStream();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
[java] view
plaincopy
/*
服务端:
*/
import java.net.*;
import java.io.*;
class PicServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
Socket s=ss.accept();
InputStream in=s.getInputStream();
FileOutputStream fos=new FileOutputStream("f:\\server.jpg");
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1)
{
fos.write(buf,0,len);
}
OutputStream out=s.getOutputStream();
out.write("图片已收到".getBytes());
fos.close();
s.close();
ss.close();
}
}
二、网络编程(TCP-客户端并发上传图片)
[java] view
plaincopy
/*
需求:上传图片。
*/
/*
客户端:
1.服务端点。
2.读取客户端已有的图片数据。
3.通过socket输出流将数据发给服务端。
4.读取服务端反馈信息。
5.关闭。
*/
import java.net.*;
import java.io.*;
class PicClient
{
public static void main(String[] args)throws Exception
{
if(args.length!=1)
{
System.out.println("请选择一个jpg格式的图片。");
return;
}
File file=new File(args[0]);
if(!(file.exists()&&file.isFile()))
{
System.out.println("该文件有问题,要么存在,要么不是文件");
return;
}
if(!file.getName().endsWith(".jpg"))
{
System.out.println("图片格式错误,请重新选择");
return;
}
if(file.length()>1024*1024*5)
{
System.out.println("文件过大,禁止上传!");
return;
}
Socket s=new Socket("172.16.56.237",1005);
FileInputStream fis=new FileInputStream(file);
OutputStream out=s.getOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1)
{
out.write(buf,0,len);
}
s.shutdownOutput();//告诉服务端数据已写完。(增加结束标记)
InputStream in=s.getInputStream();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
s.close();
}
}
[java] view
plaincopy
/*
服务端:
当A客户端连接上后,被服务端获取到后,服务端就在执行具体流程。这时B客户端连接的话,只能等待。
因为服务端还没有处理完A客户端的请求,还没有循环结束回来执行下一次accept方法,所以暂时获取不到
B客户端对象。
所以,为了可以让多个客户端同时并发访问服务端,那么服务端最好就是将每个客户端封装到一个
单独的线程中,这样就可以同时处理多个客户端请求。
如何定义线程呢?
只要明确了每一个客户端要在服务端执行的代码即可,将该代码存入run方法中。
*/
import java.net.*;
import java.io.*;
class PicThread implements Runnable
{
private Socket s;
PicThread(Socket s)
{
this.s=s;
}
public void run()
{
int count=1;
String ip=s.getInetAddress().getHostAddress();
try
{
System.out.println(ip+"..........connceted");
InputStream in=s.getInputStream();
//为了不覆盖
File file=new File("f:\\"+ip+"("+(count)+")"+".jpg");
while(file.exists())
file=new File("f:\\"+ip+"("+(count++)+")"+".jpg");
FileOutputStream fos=new FileOutputStream(file);
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1)
{
fos.write(buf,0,len);
}
OutputStream out=s.getOutputStream();
out.write("图片已收到".getBytes());
fos.close();
s.close();
}
catch (Exception e)
{
throw new RuntimeException(ip+"上传失败!");
}
}
}
class PicServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
while(true)
{
Socket s=ss.accept();
new Thread(new PicThread(s)).start();
}
}
}
三、网络编程(TCP-客户端并发登录)
[java] view
plaincopy
/*
客户端通过键盘录入用户名,服务端对这个用户名进行校验。
如果该用户存在,在服务端显示xxx,已登录,并在客户端显示xxx,欢迎登录。
如果该用户存在,在服务端显示xxx,尝试登录。并在客户端显示xxx,该用户不存在。
最多登录3次。
*/
import java.io.*;
import java.net.*;
class LoginClient
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("172.16.56.237",1005);
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
for(int i=0;i<3;i++)
{
String line=bufr.readLine();
if(line==null)
break;
out.println(line);
String info=bufIn.readLine();
System.out.println("info:"+info);
if(info.contains("欢迎"))
break;
}
bufr.close();
s.close();
}
}
[java] view
plaincopy
/*
服务端
*/
import java.io.*;
import java.net.*;
class UserThread implements Runnable
{
private Socket s;
UserThread(Socket s)
{
this.s=s;
}
public void run()
{
String ip=s.getInetAddress().getHostAddress();
try
{
for(int i=0;i<3;i++)
{
BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
String name=bufIn.readLine();
if(name==null)
return;
BufferedReader bufr=new BufferedReader(new FileReader("e:\\user.txt"));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
String line=null;
boolean flag=false;
while((line=bufr.readLine())!=null)
{
if(line.equals(name))
{
flag=true;
break;
}
}
if(flag)
{
System.out.println(name+",已登录");
out.println(name+",欢迎光临。");
}
else
{
System.out.println(name+",尝试登录。");
out.println(name+",用户名不存在。");
}
}
s.close();
}
catch (Exception e)
{
throw new RuntimeException(ip+"校验失败");
}
}
}
class LoginServer
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
while(true)
{
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
四、网络编程(浏览器客户端-自定义服务端)
[java] view
plaincopy
/*
演示客户端和服务端。
1.
客户端:浏览器
服务端:自定义
*/
import java.net.*;
import java.io.*;
class ServerDemo
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("客户端你好");//输出HTML文本
s.close();
ss.close();
}
}
五、网络编程(浏览器客户端-Tomcat服务端)
1.下载好Tomcat服务端,解压到任意路径。
2.进入Tomcat文件夹的bin目录下,点击startup.bat文件,启动Tomcat服务器。
可以看到配置信息里面的服务器端口:8080
3.进入浏览器输入: http://172.16.56.237:8080/ 打开了Tomcat网页。
这样的话,自己写个HMTL:
[html] view
plaincopy
<html>
<body>
<h1>
这是我的第一个网页
<h1>
<font size=5 color=red>欢迎光临</font>
<div>
1234567890</br>
3456789090</br>
5678987654</br>
</div>
</body>
</html>
保存成index.html文件。然后在Tomcat文件夹的webapps下建立一个myweb文件夹,将index.html放入。
在浏览器中指定具体服务器要打开html文件的路径:
http://172.16.56.237:8080//myweb/index.html
六、网络编程(自定义浏览器-Tomcat服务端)
[java] view
plaincopy
/*
客户端:浏览器
服务端:Tomcat服务器
*/
import java.net.*;
import java.io.*;
class ServerDemo
{
public static void main(String[] args)throws Exception
{
ServerSocket ss=new ServerSocket(1005);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress());
InputStream in=s.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
System.out.println(new String(buf,0,len));
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("<font color='red' sixe'10'>客户端你好</font>");//输出HTML文本
s.close();
ss.close();
}
}
运行自定义服务器后,在浏览器输入地址:http://172.16.56.237:1005/
172.16.56.237
GET / HTTP/1.1
Host: 172.16.56.237:1005
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like G
ecko) Chrome/21.0.1180.83 Safari/537.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3
这些都是浏览器向服务器发送请求的信息。包含浏览器的信息。
[java] view
plaincopy
/*模仿IE浏览器从Tomcat服务器读取index.html
*/
import java.io.*;
import java.net.*;
class MyIE
{
public static void main(String[] args)throws Exception
{
Socket s=new Socket("172.16.56.237",8080);
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("GET /myweb/index.html HTTP/1.1");//浏览器请求的文件目录
out.println("Accept: */*");//浏览器支持的文件 */* 支持所有
out.println("Accept-Language: zh-CN");//浏览器支持的语言
out.println("Host: 172.16.56.237:1005");//浏览器请求的地址
out.println("Connection: closed");//连接状态 closed 数据发送完毕,结束
out.println();
out.println();
BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null)
{
System.out.println(line);
}
s.close();
}
}
七、网络编程(自定义图形界面浏览器-Tomcat服务端)
[java] view
plaincopy
/*
自定义图形界面浏览器-Tomcat服务端:
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class MyIEByGUI
{
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okBut;
MyIEByGUI()
{
init();
}
public void init()
{
f=new Frame("my window");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf=new TextField(60);
but=new Button("转到");
ta=new TextArea(25 ,70);// 行,列
d=new Dialog(f,"提示信息",true);//第3个参数:指定在显示的时候是否阻止用户将内容输入到其他顶级窗口中。
d.setBounds(400,200,240,150);
d.setLayout(new FlowLayout());
lab=new Label();
okBut=new Button("确定");
d.add(lab);
d.add(okBut);
f.add(tf);
f.add(but);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
try
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
okBut.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
d.setVisible(false);
}
});
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
}
private void showDir()throws Exception
{
ta.setText("");//清空
String url=tf.getText();// http://172.16.56.237:8080/myweb/index.html
int index1=url.indexOf("//")+2;
int index2=url.indexOf("/",index1);
String str=url.substring(index1,index2);
String[] arr=str.split(":");
String host=arr[0];
int port=Integer.parseInt(arr[1]);
String path=url.substring(index2);
//ta.setText(str+"..."+path);//测试
Socket s=new Socket(host,port);
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("GET "+path+" HTTP/1.1");//浏览器请求的文件目录
out.println("Accept: */*");//浏览器支持的文件 */* 支持所有
out.println("Accept-Language: zh-CN");//浏览器支持的语言
out.println("Host: 172.16.56.237:1005");//浏览器请求的地址
out.println("Connection: closed");//连接状态 closed 数据发送完毕,结束
out.println();
out.println();
BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream()));
String line=null;
while((line=bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}
s.close();
}
public static void main(String[] args)
{
new MyIEByGUI();
}
}
八、网络编程(URL-URLConnection)
[java] view
plaincopy
/*
String getFile()
获取此 URL 的文件名。
String getHost()
获取此 URL 的主机名(如果适用)。
String getPath()
获取此 URL 的路径部分。
int getPort()
获取此 URL 的端口号。
String getProtocol()
获取此 URL 的协议名称。
String getQuery()
获取此 URL 的查询部分。
*/
import java.net.*;
import java.io.*;
class URLDemo
{
public static void main(String[] args)throws MalformedURLException
{
URL url=new URL("http://172.16.56.237/myweb/index.html?name=yangcheng&age=21");
System.out.println("getProtocol:"+url.getProtocol());
System.out.println("getHost:"+url.getHost());
System.out.println("getPort:"+url.getPort());
System.out.println("getPath:"+url.getPath());
System.out.println("getFile:"+url.getFile());
System.out.println("getQuery:"+url.getQuery());
/*
int port=getPort();
if(port==-1)
port=80;
*/
}
}
[java] view
plaincopy
/*
URLConnection:
*/
import java.net.*;
import java.io.*;
class URLConnectionDemo
{
public static void main(String[] args)throws Exception
{
URL url=new URL("http://172.16.56.237:8080/myweb/index.html");
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
System.out.println(new String(buf,0,len));
}
}
既然如此,那么:
[java] view
plaincopy
/*
通过URLConnection拆封:
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class MyIEByGUI2
{
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okBut;
MyIEByGUI2()
{
init();
}
public void init()
{
f=new Frame("my window");
f.setBounds(300,100,600,500);
f.setLayout(new FlowLayout());
tf=new TextField(60);
but=new Button("转到");
ta=new TextArea(25 ,70);// 行,列
d=new Dialog(f,"提示信息",true);//第3个参数:指定在显示的时候是否阻止用户将内容输入到其他顶级窗口中。
d.setBounds(400,200,240,150);
d.setLayout(new FlowLayout());
lab=new Label();
okBut=new Button("确定");
d.add(lab);
d.add(okBut);
f.add(tf);
f.add(but);
f.add(ta);
myEvent();
f.setVisible(true);
}
private void myEvent()
{
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tf.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
try
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
showDir();
}
catch (Exception ee)
{
String info="您输入的地址是错误的,请重新输入!";
lab.setText(info);
d.setVisible(true);
}
}
});
okBut.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
d.setVisible(false);
}
});
d.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
d.setVisible(false);
}
});
okBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.setVisible(false);
}
});
}
private void showDir()throws Exception
{
ta.setText("");//清空
String urlPath=tf.getText();// http://172.16.56.237:8080/myweb/index.html
URL url=new URL(urlPath);
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
byte[] buf=new byte[1024];
int len=in.read(buf);
ta.setText(new String(buf,0,len));
}
public static void main(String[] args)
{
new MyIEByGUI2();
}
}
九、网络编程(小知识点)
Socket类:
Socket() :通过系统默认类型的 SocketImpl 创建未连接套接字
void connect(SocketAddress endpoint) :将此套接字连接到服务器。
InetSocketAddress类:
而:InetSocketAddress继承自SocketAddress
InetSocketAddress类实现 IP 套接字地址(IP 地址 + 端口号)。它还可以是一个对(主机名 + 端口号),在此情况下,将尝试解析主机名。如果解析失败,则该地址将被视为未解析 地址,但是其在某些情形下仍然可以使用,比如通过代理连接。
而InetAddress类实现 IP地址。
ServerSocket类:
public ServerSocket(int port,int backlog)throws IOException
利用指定的 backlog 创建服务器套接字并将其绑定到指定的本地端口号。
端口号 0 在所有空闲端口上创建套接字。
port - 指定的端口;或者为 0,表示使用任何空闲端口。
backlog - 队列的最大长度。也就是联机数。
十、网络编程(域名解析)
例如:
要访问www.baidu.com
先查看本地的hosts文件(域名和对应的IP缓存)有没有www.baidu.com的IP。有的话,直接到hosts文件www.baidu.com对应的IP地址去访问。如果没有则会去DNS服务器找www.baidu.com的对应IP。
hosts文件最常用来屏蔽危险连接。例如将不安全的域名直接在hosts文件中和127.0.0.1回环地址绑定。这个危险的网站就不会去DNS服务器找IP了,网站也就无法打开。
相关文章推荐
- 黑马程序员_Java基础_网络编程相关小项目
- 黑马程序员_Java基础_网络编程基础相关
- 黑马程序员_Java基础--网络编程
- 黑马程序员---Java基础--23天(网络编程之一)
- 黑马程序员-Java基础-网络编程
- 黑马程序员-java基础学习网络编程2
- 黑马程序员 java基础之网络编程TCP
- 黑马程序员_java基础(12)网络编程之UDP
- 黑马程序员:Java基础总结----网络编程
- 黑马程序员 java基础<八>--网络编程(2)
- 黑马程序员-Java语言基础– 网络编程 第23-24天
- 黑马程序员 java基础之网络编程UDP
- 黑马程序员---Java基础--24天(网络编程之二)
- 黑马程序员----JAVA基础之GUI可视化编程与枚举&网络编程
- 黑马程序员Java培训、Android培训_网络编程的基础知识
- 黑马程序员-java学习基础加强之网络编程
- 黑马程序员Java基础之网络编程(net)
- 黑马程序员---java基础之网络编程
- 黑马程序员-----java基础十九(java之网络编程)
- 黑马程序员 Java基础 ---> 网络编程