通讯过程
客户端:
public class MyClient {
public static void main(String[] args) throws IOException {
//客户端 连接Server发布的服务
Socket socket = new Socket("127.0.0.1", 8080);
//客户端向服务端做出反馈(向服务端发送消息)
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello server".getBytes());
//接受服务端发送的消息 InputStream
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
inputStream.read(bytes);
System.out.println(new String(bytes));
socket.close();
outputStream.close();
inputStream.close();
}
}
public class MyServer {
public static void main(String[] args) throws IOException {
//绑定服务的端口,ip:为本机Ip
//暴漏了一个 服务,该服务的地址: 本机ip:9999
ServerSocket serverSocket = new ServerSocket(8080);
Socket accept = serverSocket.accept();
System.out.println("与客户端连接成功");
//接受客户端的消息
InputStream inputStream = accept.getInputStream();
byte[] bytes = new byte[1024];
inputStream.read(bytes);
System.out.println(new String(bytes));
//服务端向客户端发送消息 Output
OutputStream outputStream = accept.getOutputStream();
outputStream.write("hello client".getBytes());
//关闭通讯
serverSocket.close();
accept.close();
inputStream.close();
outputStream.close();
}
}
服务器端给客户端发送文件:
服务器端:
public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
Socket accept = serverSocket.accept();
System.out.println("已接受客户端");
OutputStream outputStream = accept.getOutputStream();
//从硬盘写入内存当中
FileInputStream in = new FileInputStream("G:\\video.zip");
byte[] bytes = new byte[1024];
int len =-1;
while ((len = in.read(bytes))!= -1){
outputStream.write(bytes,0,len);
}
outputStream.close();
serverSocket.close();
accept.close();
in.close();
}
}
客户端:
public class FileClient {
public static void main(String[] args) throws IOException {
Socket socket1 = new Socket("127.0.0.1", 8080);
FileOutputStream outputStream = new FileOutputStream("G:\\aa.zip");
InputStream inputStream = socket1.getInputStream();
int len = -1;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
outputStream.write(bytes,0,len);
}
socket1.close();
outputStream.close();
inputStream.close();
}
}