- 客户端使用的是Socket类,服务器端使用的是ServerSocket类。
- 服务器端使用的网络字节流是属于客户端的。
- 客户端的代码如下:
package bao8;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MyClient
{
public static void main(String[] args) throws Exception
{
Socket socket=new Socket("127.0.0.1",2333);
OutputStream outputStream = socket.getOutputStream();
FileInputStream fileInputStream=new FileInputStream("D:\\jisuanqi.jpg");
byte [] array=new byte[1024];
int item=0;
while ((item=fileInputStream.read(array))!=-1)
{
outputStream.write(array,0,item);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
while ((item=inputStream.read(array))!=-1)
{
String s = new String(array, 0, item);
System.out.println(s);
}
fileInputStream.close();
socket.close();
}
}
- 服务器端的代码如下:
package bao8;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
public class MyServer
{
public static void main(String[] args) throws Exception
{
ServerSocket serverSocket=new ServerSocket(2333);
while (true)
{
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
String str = UUID.randomUUID().toString();
String replaceStr = str.replace("-", "");
FileOutputStream fileOutputStream=new FileOutputStream("f:\\"+replaceStr+".jpg");
byte [] array=new byte[1024];
int item=0;
while ((item=inputStream.read(array))!=-1)
{
fileOutputStream.write(array,0,item);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("文件上传成功!".getBytes());
fileOutputStream.close();
socket.close();
}
}
}