---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
这部分的知识点主要有:
1.TCP传输的几个应用;
2.浏览器访问服务器。
一、TCP传输的几个应用
1.TCP上传图片
import java.io.*;
import java.net.*;
class UploadPicClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.31.1",10010);
FileInputStream fis = new FileInputStream("client.png");
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();
}
}
class UploadPicServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10010);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+" connected...");
InputStream in = s.getInputStream();
FileOutputStream fos = new FileOutputStream("server.png");
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();
}
}
2.客户端并发上传图片
要求通过键盘输入要上传的图片路径,并对格式和大小有要求。
import java.net.*;
import java.io.*;
class UploadPicByThreadClient
{
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;
}
//判断是不是jpg格式的文件
if(!file.getName().endsWith(".jpg"))
{
System.out.println("文件格式不正确,请选择jpg文件");
return;
}
//文件体积不能超过5M
if(file.length()>1024*1024*5)
{
System.out.println("文件体积过大,不能大于5兆");
return;
}
Socket s = new Socket("192.168.31.1",10011);
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 bufLen = in.read(bufIn);
System.out.println(new String(bufIn,0,bufLen));
fis.close();
s.close();
}
}
class UploadPicThread implements Runnable
{
private Socket s;
UploadPicThread(Socket s)
{
this.s = s;
}
public void run()
{
String ip = this.s.getInetAddress().getHostAddress();
System.out.println(ip+" connected...");
FileOutputStream fos = null;
int count = 1;
try
{
//使用连接到服务器的客户端的ip地址来命名上传的图片
File file = new File(ip+".jpg");
//如果存在同名文件,则在后面加上数字序号
while(file.exists())//这里不能用if判断,要用while循环
file = new File(ip+"("+(count++)+")"+".jpg");
fos = new FileOutputStream(file);
InputStream in = this.s.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))!=-1)
{
fos.write(buf,0,len);
}
OutputStream out = this.s.getOutputStream();
out.write("图片上传成功".getBytes());
}
catch (Exception e)
{
throw new RuntimeException("图片上传异常");
}
finally
{
if(fos!=null)
try
{
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("写入流关闭异常");
}
try
{
this.s.close();
}
catch (IOException e)
{
throw new RuntimeException("socket关闭异常");
}
}
}
}
class UploadPicByThreadServer
{
private Socket s;
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10011);
while(true)
{
Socket s = ss.accept();
new Thread(new UploadPicThread(s)).start();
}
}
}
3.客户端并发登陆
需求:客户通过键盘录入用户名,服务端对这个用户名进行校验。如果该用户存在,在服务端显示“xxx,已登录”,在客户端显示“xxx,欢迎光临”;如果该用户不存在,在服务端显示“xxx,尝试登陆”,在客户端显示“xxx,该用户不存在”。最多登陆三次。
import java.io.*;
import java.net.*;
class LoginClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.31.1",10001);
BufferedReader bufr = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader bufIn = new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter bufOut = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
for(int i=0;i<3;i++)
{
String line = bufr.readLine();
if(line==null)
break;
bufOut.write(line);
bufOut.newLine();
bufOut.flush();
String info = bufIn.readLine();
System.out.println(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 = this.s.getInetAddress().getHostAddress();
System.out.println(ip+" connected...");
try
{
BufferedReader bufIn = new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter bufOut = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
for(int i=0;i<3;i++)
{
String name = bufIn.readLine();
BufferedReader bufr = new BufferedReader(
new FileReader("users.txt"));
boolean flag = false;
String line = null;
while((line=bufr.readLine())!=null)
{
if(line.equals(name))
{
flag = true;
break;
}
}
if(flag)
{
System.out.println(name+",已登录");
bufOut.write(name+",欢迎光临");
bufOut.newLine();
bufOut.flush();
break;
}
else
{
System.out.println(name+",尝试登陆");
bufOut.write(name+",该用户不存在");
bufOut.newLine();
bufOut.flush();
}
bufr.close();
}
}
catch(Exception e)
{
throw new RuntimeException("验证异常");
}
finally
{
try
{
this.s.close();
}
catch (IOException e)
{
throw new RuntimeException("socket关闭异常");
}
}
}
}
class LoginServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10001);
System.out.println(ss);
while(true)
{
Socket s = ss.accept();
new Thread(new UserThread(s)).start();
}
}
}
二、浏览器访问服务端
1.浏览器客户端访问自定义服务端
import java.net.*;
import java.io.*;
class ServerDemo
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10015);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+" connected...");
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
pw.println("你好啊,帅哥!");
s.close();
//ss.close();
}
}
通过浏览器访问http://xxx.xxx.xxx.xxx:10015访问服务端,可以显示服务端的反馈信息。其中xxx.xxx.xxx.xxx表示本机ip。
2.浏览器访问Tomcat服务端
3.自定义浏览器访问Tomcat服务端
import java.io.*;
import java.net.*;
class MyIE
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.31.1",8080);
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
//向服务器发送请求数据头
pw.println("GET /myweb/demo.html HTTP/1.1");
pw.println("Accept: */*");
pw.println("Accept-Language: zh-CN");
pw.println("Host: 192.168.31.1:10015");
pw.println("Connection: Keep-Alive");
pw.println();
//读取服务器发送过来的数据
BufferedReader bufIn = new BufferedReader(
new InputStreamReader(s.getInputStream()));
String line = null;
while((line=bufIn.readLine())!=null)
System.out.println(line);
s.close();
}
}
4.URL和URLConnection
用URLConnection对象获取的服务端数据,没有响应头
import java.net.*;
class URLDemo
{
public static void main(String[] args) throws MalformedURLException
{
URL url = new URL("http://192.168.31.1:8080/myweb/demo.html?name=zhangsan&age=30");
System.out.println("getFile():"+url.getFile());//获取此URL的文件名
System.out.println("getHost():"+url.getHost());//获取此URL的主机名
System.out.println("getPath():"+url.getPath());//获取此URL的路径部分
System.out.println("getPort():"+url.getPort());//获取此URL的端口号
System.out.println("getProtocol():"+url.getProtocol());//获取此URL的协议名称
System.out.println("getQuery():"+url.getQuery());//获取此URL的查询部分
}
}
import java.io.*;
import java.net.*;
class URLConnectionDemo
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://192.168.31.1:8080/myweb/demo.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));
}
}
5、小知识点
(1)Socket有一个函数connect(SocketAddress endPoint),其中SocketAddress封装的是IP地址和端口,二InetAddress封装的只是IP地址。
(2)ServerSocket有一个构造函数ServerSocket(int port,int backlog),其中backlog表示能连接到服务端的客户端的最大数量。
---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net