还是TCP协议
现在传东西不会丢失了,但我想我文件的名字传过去,接受的时候该怎么写?客户端:
package jj;
import
import
import
import
import
import
import
import
import
import
public class TcpOneToManyClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 7751);
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
String filename="D://myeclips//新建文件夹(2)//XuLieHua//bin//com//guo//big//Student.class";
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
int c = 0;
// dos.writeBytes(filename);
while((c = dis.read()) != -1) {
dos.write(c);
}
dos.close();
dis.close();
}
}
服务器端:
package jj;
import
import
import
import
import
import
import
import
import
import
public class TcpOneToManyServer {
public static int socketNumber = 1;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(7751);
System.out.println("Server is running");
while(true) {
Socket socket = serverSocket.accept();
SocketHandle socketHandle = new SocketHandle(socket, socketNumber++);
socketHandle.start();
}
}
}
class SocketHandle extends Thread {
private Socket socket;
private int socketNumber;
public SocketHandle(Socket socket, int socketNumber) {
this.socket = socket;
this.socketNumber = socketNumber;
}
public void run(){
try {
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("D://" + socketNumber + ".class")));
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream());
//int str=dis.readInt();
// System.out.println(str);
int c = 0;
while((c = dis.read()) != -1) {
dos.write(c);
}
pw.println("aa");
pw.flush();
pw.close();
dos.close();
dis.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}