|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
服务器端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args) {
try {
// 创建服务器Socket,监听指定端口
ServerSocket serverSocket = new ServerSocket(1314);
System.out.println("服务器启动,等待客户端连接...");
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("客户端连接成功!");
// 获取输入流
InputStream inputStream = clientSocket.getInputStream();
// 创建输出流,保存文件
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Server.txt");
// 读取数据并写入文件
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 关闭流
fileOutputStream.close();
inputStream.close();
clientSocket.close();
serverSocket.close();
System.out.println("文件接收成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
import java.io.*;
import java.net.Socket;
public class EchoClient {
public static void main(String[] args) {
try {
// 创建Socket,连接服务器
Socket socket = new Socket("127.0.0.1", 1314);
// 创建文件输入流,读取文件
FileInputStream fileInputStream = new FileInputStream("D:\\Client.txt");
// 获取输出流,发送数据
OutputStream outputStream = socket.getOutputStream();
// 读取文件并发送数据
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流
fileInputStream.close();
outputStream.close();
socket.close();
System.out.println("文件发送成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
有什么问题嘛,为什么连接失败了
|
|