您的位置:首页 > 理论基础 > 计算机网络

Java基础视频教程第24天_网络编程二(了解即可)

2015-03-20 08:32 579 查看
一、网络编程——TCP-上传图片
import java.io.*;
import java.net.*;

class Client
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.254",20000);

BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("1.jpg"));

BufferedOutputStream bufos = new BufferedOutputStream(s.getOutputStream());

int by = 0;
while((by=bufis.read())!=-1)
{
bufos.write(by);
}

s.shutdownOutput();//定义结束标记

BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = bufIn.readLine();
System.out.println("server say: "+line);

bufis.close();
s.close();
}
}

class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(20000);
Socket s = ss.accept();

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"......connected");

BufferedInputStream bufis = new BufferedInputStream(s.getInputStream());

BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("copy_1.jpg"));
int by = 0;
while((by=bufis.read())!=-1)//当客户端读到s.shutdownoutput();时,这里才读到-1
{
bufos.write(by);
}

PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println("上传成功");

bufos.close();
s.close();
ss.close();
}
}

二、网络编程——TCP-客户端并发上传图片

import java.io.*;
import java.net.*;

class Client
{
public static void main(String[] args) throws Exception
{
if(args.length!=1)
{
System.out.println("一次只能传一张图片!");
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("192.168.1.254",20000);

BufferedInputStream bufis = new BufferedInputStream(new FileInputStream(file));

BufferedOutputStream bufos = new BufferedOutputStream(s.getOutputStream());

int by = 0;
while((by=bufis.read())!=-1)
{
bufos.write(by);
}

s.shutdownOutput();//定义结束标记

BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = bufIn.readLine();
System.out.println("server say: "+line);

bufis.close();
s.close();
}
}

class PicThread implements Runnable
{
private Socket s;

PicThread(Socket s)
{
this.s = s;
}
public void run()
{
int count = 0;

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"......connected");

try
{
File file = new File(ip+".jpg");

while(file.exists())
file = new File(ip+"("+(++count)+")"+".jpg");

BufferedInputStream bufis = new BufferedInputStream(s.getInputStream());

BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream(file));
int by = 0;
while((by=bufis.read())!=-1)//当客户端读到s.shutdowmOutput();时,这里才读到-1
{
bufos.write(by);
}

PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println("上传成功");

bufos.close();
s.close();
}
catch (Exception e)
{
throw new RuntimeException(ip+"上传失败");
}
}
}

class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(20000);
while(true)
{
Socket s = ss.accept();

new Thread(new PicThread(s)).start();
}
//ss.close();
}
}

三、网络编程——TCP-客户端并发登录

import java.io.*;
import java.net.*;

class Client
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.254",10011);

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 name = bufr.readLine();
if(name==null)
break;

out.println(name);

String info = bufIn.readLine();
System.out.println("information: "+info);

if(info.contains("欢迎"))
break;
}
bufr.close();
s.close();
}
}

class UserThread implements Runnable
{
private Socket s;
UserThread(Socket s)
{
this.s = s;
}
public void run()
{
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+".....connected");
try
{
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

BufferedReader bufr = new BufferedReader(new FileReader("user.txt"));

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

for (int x=0 ;x<3 ;x++ )
{
String line = bufIn.readLine();//当客户端读到s.close();时,这里才接受到null。
if(line==null)
break;

String name = null;
boolean flag = false;
while((name=bufr.readLine())!=null)
{
if(line.equals(name))
{
flag = true;
break;
}
}
if(flag)
{
System.out.println(line+",已登录");
out.println(line+",欢迎登录!");
break;
}
else
{
System.out.println(line+",尝试登录");
out.println(line+",用户名错误");
}
}
bufr.close();
s.close();
}
catch (Exception e)
{
throw new RuntimeException(ip+"校验失败");
}
}
}

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

四、网络编程——浏览器客户端-自定义服务端

== telnet 是windows中的一个远程登录命令。可以去连接网络中的任意一台主机(在dos命令行下连接)。连接之后可以对这台主机进行命令式的配置。

打开方式:
telnet 主机地址 端口号
例如: telnet 192.168.1.254 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();

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip);

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

out.println("<font color='red' size='7'>客户端,你好!</font>");

s.close();
ss.close();
}
}

五、网络编程——浏览器客户端-Tomcat服务端



六、网络编程——自定义浏览器-Tomcat服务端

代码一:
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();

String ip = s.getInetAddress().getHostAddress();
System.out.println(ip);

InputStream in = s.getInputStream();
byte[] buf = new byte[1024*4];
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' size='7'>客户端,你好!</font>");

s.close();
ss.close();
}
}

=======================客户端给服务端发送请求
http://192.168.1.254:11000/myweb/demo.html 主机名 端口号/资源路径/资源

GET /myweb/demo.html HTTP/1.1
协议版本为:HTTP/1.1

Accept: text/html, application/xhtml+xml,
支持文件

Accept-Language: zh-CN
支持语言:简体中文

User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko

Accept-Encoding: gzip, deflate
支持的封装形式:压缩,

Host: 192.168.1.254:11000
主机:地址:端口

DNT: 1

Connection: Keep-Alive
连接方式:保持存活

=======================================
import java.io.*;
import java.net.*;

class MyIE
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.254",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: 10.20.4.121:11000");
//out.println("Connection: Keep-Alive");
out.println("Connection: 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();
}
}

==================服务端给客户端发送的应答模式
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"187-1421566687476"
Last-Modified: Sun, 18 Jan 2015 07:38:07 GMT
Content-Type: text/html
Content-Length: 187
Date: Mon, 19 Jan 2015 05:37:55 GMT
Connection: close

<html>

<body>
<h1>这是我的主页</h1>
<font size=5 color=red>欢迎光临
<div>
床前明月光</br>
疑是地上霜</br>
举头望明月</br>
低头思故乡</br>
</body>
</html>
==============================================

七、网络编程——自定义图形界面浏览器-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;

MyIEByGUI()
{
init();
}

public void init()
{
f = new Frame("my IE");
f.setBounds(300,200,600,400);
f.setLayout(new FlowLayout());

tf = new TextField(50);
f.add(tf);

but = new Button("转到");
f.add(but);

ta = new TextArea(15,60);
f.add(ta);

myEvent();

f.setVisible(true);
}

public void myEvent()
{
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 ex)
{
}

}
});

but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
showDir();
}
catch (Exception ex)
{
}
}
});
}

public void showDir() throws Exception
{
ta.setText("");
String url = tf.getText();//http://192.168.1.254:8080/myweb/demo.html

int index1 = url.indexOf("//")+2;
int index2 = url.indexOf("/",index1);

String str = url.substring(index1,index2);
String path = url.substring(index2);

String[] arr = str.split(":");

String host = arr[0];
int port = Integer.parseInt(arr[1]);

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: 10.20.10.5:11000");
out.println("Connection: closed");

out.println();
out.println();

BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = bufr.readLine();
while((line=bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}
s.close();
}

public static void main(String[] args)
{
new MyIEByGUI();
}
}

八、网络编程——URL-URLConnection

URL: 统一资源定位符。
URL: 范围比 URL 大。

代码一:
import java.net.*;

class URLDemo
{
public static void main(String[] args) throws MalformedURLException
{
URL url = new URL("http://192.168.1.254:8080/myweb/demo.html?name=haha&age=30");

System.out.println("getProtocol() : "+url.getProtocol()); //http
System.out.println("getHost() : "+url.getHost()); //10.20.4.121
System.out.println("getPort() : "+url.getPort()); //8080
System.out.println("getPath() : "+url.getPath()); //myweb/demo.html
System.out.println("getFile() : "+url.getFile()); //myweb/demo.html?name=haha&age=30
System.out.println("getQuery() : "+url.getQuery()); //name=haha&age=30

/*

int port = url.getPort();
if(port==-1)
port = 80;

*/
}
}

代码二:
import java.net.*;
import java.io.*;

class URLConnectionDemo
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://192.168.1.254:8080/myweb/demo.html");
//URL可以封装成一个Socket对象,但是Socket对象走的是传输层。

//所以可以获取应用层URLConnection的子类对象(URLConnection 是一个抽象类。)
URLConnection conn = url.openConnection();

System.out.println(conn);
//sun.net.www.protocol.http.HttpURLConnection:http://192.168.1.254:8080/myweb/demo.html

InputStream in = conn.getInputStream();
//url.openStream();等同于 url.openConnection().getInputStream();

byte[] buf = new byte[1024*4];

int len = in.read(buf);

System.out.println(new String(buf,0,len));
}
}

=======代码二接收到的数据没有了响应头。

九、网络编程——小知识点

Socket();空参数构造时,可以通过connect(SocketAddress endpoint);方法指定主机名和端口。

SocketAddress 是一个抽象类,可以通过其子类 InetSocketAddress 创建对象。

InetSocketAddress(String hostname, int port);该构造函数可以指定主机和端口号。

ServerSocket(int port, int backlog);该构造方法可以指定端口和客户端的最大连接数。

十、网络编程——域名解析

本地localhost映射关系存储路径:
C:\Windows\System32\drivers\etc\hosts

当在网址栏输入某一个网址,需要先将域名进行解析。
解析先在本机hosts中查找对应的域名,本机没有再到DNS服务器列表查找。

35天版——day27-24-常见网络结构

C/S : client/server
弊端:
该结构的软件,客户端和服务端都需要编写。
开发成本较高,维护较为麻烦。

优势:
客户端在本地可以分担一部分运算。

B/S : browser/server
优势:
该结构的软件,只开发服务器端,不开发客户端,因为客户端直接由浏览器取代。
开发成本相对较低,维护更为简单。

缺点:
所有运算都在服务器端完成。
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: