JAVASE----19----网络编程2

时间:2022-12-15 13:30:48

上传图片


package net2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/*
客户端:
1,服务端点
2,读取客户端已有的图片数据
3,通过socket输出流将数据发给服务端
4,读取服务端反馈信息
5,关闭
*/
public class PicClient {


public static void main(String[] args) throws Exception {

Socket s=new Socket("192.168.1.102", 10029);
BufferedInputStream bufr=new BufferedInputStream(new FileInputStream("C:\\1.jpg"));
OutputStream out=s.getOutputStream();
byte[]buf=new byte[1024];
int len=0;
while((len=bufr.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));
bufr.close();
s.close();
}

}



package net2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
* 服务端
*/
public class PicServer {

public static void main(String[] args) throws Exception {

ServerSocket ss=new ServerSocket(10029);
Socket s=ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println("ip" + ip + "connect...");
InputStream in= s.getInputStream();
FileOutputStream fos=new FileOutputStream("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();
}

}

JAVASE----19----网络编程2

这个服务端有局限性,当A客户端连接上后,被服务端收到,服务端执行具体流程,这时B客户端连接只有等待。
因为服务端还没有处理完A客户端的请求,还有循环回来执行下次accept方法,所以暂时获取不到B客户端对象。
  那么为了让多个客户端并发访问服务端,那么服务端最好将每个客户端封装进单独的线程中,这样就可以同时处理多个客户端请求


如何定义线程呢? 只要明确了每一个客户端要在服务端执行的代码即可,将该代码存入run方法中

package net2;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/*
客户端:
1,服务端点
2,读取客户端已有的图片数据
3,通过socket输出流将数据发给服务端
4,读取服务端反馈信息
5,关闭
*/
public 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("文件过大,没安好心");
// }
Socket s=new Socket("192.168.1.102", 10029);
BufferedInputStream bufr=new BufferedInputStream(new FileInputStream("c:\\1.jpg"));
OutputStream out=s.getOutputStream();
byte[]buf=new byte[1024];
int len=0;
while((len=bufr.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));
bufr.close();
s.close();
}

}


package net2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
* 服务端
*
*/
public class PicServer {

public static void main(String[] args) throws Exception {

ServerSocket ss=new ServerSocket(10029);

while(true)
{
Socket s=ss.accept();
new Thread(new PicThread(s)).start();
}
}

}


package net2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class PicThread implements Runnable {

private Socket s;
PicThread(Socket s)
{
this.s=s;
}
@Override
public void run() {
int count=1;
String ip = s.getInetAddress().getHostAddress();
try
{

System.out.println("ip" + ip + "connect...");
InputStream in= s.getInputStream();

File file=new File(ip+"("+count+")"+".jpg");
while(file.exists())
{
file=new File(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+"上传失败");
}
}



}

JAVASE----19----网络编程2JAVASE----19----网络编程2




练习:
客户端通过键盘录入用户名,服务端对这个用户名进行校验,如果该用户名存在,在服务端显示XXX已登录,并在客户端显示XXX欢迎光临,
如果该用户不存在,在服务端显示XXX,尝试登录,并在客户端显示XXX用户名不存在,最多就登录3次


package net2;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class LoginClient {


public static void main(String[] args) throws Exception {
Socket s=new Socket("192.168.1.102", 10030);
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 x=0;x<3;x++)
{
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();
}

}



package net2;


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

public class LoginServer {


public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10030);
while(true)
{
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}
}

}


package net2;

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

public class UserThread implements Runnable {


private Socket s;
UserThread(Socket s)
{
this.s=s;
}
@Override
public void run() {
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"...connected");
try {

for(int x=0;x<3;x++)
{
BufferedReader bufIn = new BufferedReader(new InputStreamReader(
s.getInputStream()));
String name=bufIn.readLine();
if(name==null)
break;
BufferedReader bufr = new BufferedReader(new FileReader("c:\\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+",欢迎光临");
break;
}
else
{
System.out.println(name+",尝试登录");
out.println(name+",用户名不存在");
}

}
s.close();
} catch (Exception e) {
throw new RuntimeException(ip+"校验失败");
}

}


}

这个标记判断有点问题,目前还未解决。











package net2;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/*
* 演示客户端和服务端
1,客户端:浏览器
服务端:自定义
2,客户端:浏览器
服务端:TomCat服务器
*/

public class ServerDemo {


public static void main(String[] args) throws Exception {

ServerSocket ss=new ServerSocket(18000);
Socket s=ss.accept();

PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println(s.getInetAddress().getHostAddress()+"<font color='red' size='7'>访问</font>");
s.close();
//ss.close();
}


}

JAVASE----19----网络编程2



JAVASE----19----网络编程2



获取浏览器的请求信息:

JAVASE----19----网络编程2



根据上面的请求消息头,可以自定义一个浏览器。


package net3;

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

public class MyIE {

/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s=new Socket("192.168.1.102",8080);
PrintWriter out=new PrintWriter(s.getOutputStream(),true);
out.println("GET /MyWeb/demo.html HTTP/1.1");
out.println("Accept: */*");
out.println("Accept-Language: zh-cn");
out.println("Host: 192.168.1.102:8080");
out.println("Connection: Keep-Alive");
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();
}

}


JAVASE----19----网络编程2打印的为消息尾和网页



加上GUI

package net3;

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.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyIEByGUI {

private Frame f;
private Button btn;
private TextField tf;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okButton;

public MyIEByGUI() {
init();
}

private void init() {

f = new Frame("my frame");
f.setBounds(300, 100, 600, 500);
f.setLayout(new FlowLayout());
btn = new Button("转到");
tf = new TextField(60); // 参数为列数
ta = new TextArea(15, 50); // 行,列
// true--必须要等待对话框的操作才能操作其他窗口
d = new Dialog(f, "提示信息:", true);
d.setBounds(400, 200, 240, 150);
d.setLayout(new FlowLayout());
lab = new Label();
okButton = new Button("确定");

d.add(lab);
d.add(okButton);

f.add(tf);
f.add(btn);
f.add(ta);

myEvent();
f.setVisible(true);
}

private void myEvent() {

f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
System.exit(0);
}
});

// 对话框右上角的X事件
d.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent e) {
d.setVisible(false);
}

});
btn.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

try {
showDir();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});

//点击确定按钮或者按空格都会关闭对话框
okButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
d.setVisible(false);
}
});

//文本框的键盘监听事件
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER) {

try {
showDir();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
}
});

}


private void showDir() throws UnknownHostException, IOException {
ta.setText("");
String url=tf.getText(); //http://192.168.1.102:8080/MyWeb/demo.html

int index1=url.indexOf("//")+2;
int index2=url.indexOf("/",index1);
//String str=url.substring(url.indexOf("//")+2);
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);

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: 192.168.1.102:8080");
out.println("Connection: Keep-Alive");
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();
}

}

JAVASE----19----网络编程2




URL



package net3;

import java.io.ObjectInputStream.GetField;
import java.net.MalformedURLException;
import java.net.URL;

//封装了传输层的socket对象
public class URLDemo {


public static void main(String[] args) throws MalformedURLException {

URL url=new URL("http://192.168.1.102/MyWeb/demo.html?name=haha&age=20");
//获取协议
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=url.getPort();
// if(port==-1)
// {
// port=80;
// }
}

}


URLConnection



package net3;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class URLConnection {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
URL url=new URL("http://192.168.1.104:8080/MyWeb/demo.html");
java.net.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));

}

}

成功打开网页并去除了消息头,这是个拆包过程,看图:
JAVASE----19----网络编程2



所以,对IE再次修改,这是吧传输层封装后的结果,只是不能进行解析:

package net3;

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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

public class MyIEByGUI {

private Frame f;
private Button btn;
private TextField tf;
private TextArea ta;
private Dialog d;
private Label lab;
private Button okButton;

public MyIEByGUI() {
init();
}

private void init() {

f = new Frame("my frame");
f.setBounds(300, 100, 600, 500);
f.setLayout(new FlowLayout());
btn = new Button("转到");
tf = new TextField(60); // 参数为列数
ta = new TextArea(15, 50); // 行,列
// true--必须要等待对话框的操作才能操作其他窗口
d = new Dialog(f, "提示信息:", true);
d.setBounds(400, 200, 240, 150);
d.setLayout(new FlowLayout());
lab = new Label();
okButton = new Button("确定");

d.add(lab);
d.add(okButton);

f.add(tf);
f.add(btn);
f.add(ta);

myEvent();
f.setVisible(true);
}

private void myEvent() {

f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
System.exit(0);
}
});

// 对话框右上角的X事件
d.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent e) {
d.setVisible(false);
}

});
btn.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

try {
showDir();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});

//点击确定按钮或者按空格都会关闭对话框
okButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
d.setVisible(false);
}
});

//文本框的键盘监听事件
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER) {

try {
showDir();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
}
});

}


private void showDir() throws UnknownHostException, IOException {
ta.setText("");
// String url=tf.getText(); //http://192.168.1.102:8080/MyWeb/demo.html
//
// int index1=url.indexOf("//")+2;
// int index2=url.indexOf("/",index1);
// //String str=url.substring(url.indexOf("//")+2);
// 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);
//
// 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: 192.168.1.102:8080");
// out.println("Connection: Keep-Alive");
// 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();

URL url=new URL("http://192.168.1.101:8080/MyWeb/demo.html");
java.net.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 MyIEByGUI();
}

}

JAVASE----19----网络编程2


最后,看一下域名解析

JAVASE----19----网络编程2


比如需要验证更新的软件,在其要访问的软件网址改成127.0.0.1 变成本机,不让其更新。