以上传图片为例,熟悉掌握TCP传输中并发访问的具体程序代码
import java.io.*;
import java.net.*;
class SocketDemo
{
public static void main(String[] args) throws Exception
{
//创建Socket对象开启Socket服务,并指定要连接的主机和端口
Socket s=new Socket("10.242.84.26",11000);
//将图片文件封装
File file=new File("F:\\1.jpg");
//建立字节输入流,并关联图片文件
FileInputStream is=new FileInputStream(file);
//获取Socket中的输出流,将字节输入流中的数据写入其中
OutputStream os=s.getOutputStream();
//获取Socket中的输入流,用于读取服务器端的反馈信息
InputStream is1=s.getInputStream();
byte[] b=new byte[1024];
int num=0;
//完成图片文件的读写
while((num=is.read(b))!=-1)
{
os.write(b,0,num);
}
//图片文件读写完成后要向服务器端发送输出结束命令
s.shutdownOutput();
//读取反馈信息
byte[] by=new byte[1024];
int num1=is1.read(by);
System.out.println(new String(by,0,num1));
//关闭资源
is.close();
s.close();
}
}
class ServerDemo4
{
public static void main(String[] args)throws Exception
{
//闯将ServerSocket对象建立服务器端
ServerSocket ss=new ServerSocket(11000);
while(true)
{
//接收客户端对象
Socket s=ss.accept();
//开启线程,用于多线程并发访问
new Thread(new ServerSocketDemo(s)).start();
}
}
}
class ServerSocketDemo implements Runnable
{
//Runnable子类初始化时就获取Socket对象
private Socket s;
ServerSocketDemo(Socket s)
{
this.s=s;
}
public void run()
{
try
{
//获取客户端的主机
String ip=s.getInetAddress().getHostAddress();
System.out.println("ip:"+ip);
//获取Socket中的输入流,读取输出流的信息
InputStream is=s.getInputStream();
int count=1;
//将文件封装
File file=new File(ip+".JPG");
//判断文件是否存在,存在则文件名加1存储
//注意要用while判断语句
while(file.exists())
file=new File(ip+"("+(count++)+")"+".JPG");
//建立输出流,用于将输入流中的数据写入指定文件
FileOutputStream os=new FileOutputStream(file);
byte[] b=new byte[1024];
int num=0;
//图片文件的写入过程
while((num=is.read(b))!=-1)
{
os.write(b,0,num);
}
//获取Socket的输出流,用于写入反馈信息
OutputStream os1=s.getOutputStream();
os1.write("传输完成".getBytes());
//关闭资源
os1.close();
s.close();
}
catch (Exception i)
{
throw new RuntimeException();
}
}
}