我开发了一个运行良好的多线程服务器!但现在我想让它第一次发送客户端连接一个字符串,然后继续以相同的常规过程接收字符串并发送文件!这是我的服务器代码
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.Scanner;
class TCPServer {
public static void main(String argv[]) throws Exception {
System.out.println("Welcome to the stream Server");
System.out.println("listening to Clients");
ServerSocket welcomeSocket = new ServerSocket(3248);
while (true) {
Socket connectionSocket = welcomeSocket.accept();
if (connectionSocket != null) {
Client client = new Client(connectionSocket);
client.start();
}
}
}
}
class Client extends Thread {
private Socket connectionSocket;
public Client(Socket c) throws IOException {
connectionSocket = c;
}
public void run() {
String path = "C:/pao/new2/";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
try {
String fileToSendStr = readFile();
File fileToSend = null;
for (File f : listOfFiles)
{
if (f.getName().equals(fileToSendStr)) {
fileToSend = f;
break;
}
}
System.out.println("Connecting to Client to recieve the part " +fileToSendStr);
if (fileToSend == null) {
}
System.out.println("Sending the chunk to Client");
long length = fileToSend.length();
byte [] longBytes = new byte[8];
ByteBuffer bbuffer = ByteBuffer.wrap(longBytes);
bbuffer.putLong(length);
connectionSocket.getOutputStream().write(longBytes);
BufferedOutputStream bout = new BufferedOutputStream(connectionSocket.getOutputStream());
BufferedInputStream bain = new BufferedInputStream(new FileInputStream(fileToSend));
byte buffer [] = new byte [1024];
int i = 0;
while((i = bain.read(buffer, 0, 1024)) >= 0){
bout.write(buffer, 0, i);
}
System.out.println("chunk sended");
bout.close();
bain.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFile() throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(
connectionSocket.getInputStream()));
return r.readLine();
}
}
想要建立连接的客户端部分不同于它建立该连接的部分。只想第一次检索一个字符串,然后该部分不再可用!