gpt4 book ai didi

java - 请使用Java中的多线程

转载 作者:行者123 更新时间:2023-12-02 03:01:13 29 4
gpt4 key购买 nike

我是一个新的java程序员,我有一个文件共享程序,我试图让它在多线程的while(true)循环中连续工作。我的服务器运行正常,但我可以使客户端连续运行,例如服务器建立连接,然后我运行客户端,但我必须手动运行它,因为文件传输后,客户端停止。下面是代码,你能帮我纠正错误吗?

import java.net.*;
import java.io.*;
public class TCPServer
{
private static ServerSocket myServer;
private static Socket myClient = null;

public static void main(String[] args) throws IOException
{

try
{
myServer = new ServerSocket(6789);
System.out.println("Server is now available...");
}
catch(Exception e)
{
System.err.println("This port is unavailable.");
System.exit(1);
}

while(true)
{
try
{
myClient = myServer.accept();
System.out.println("Connection established to : " + myClient);
Thread t = new Thread(new ConnectionThread(myClient));
t.start();
}catch(Exception e)
{
System.err.println("Connection failed...!");
}
}
}
}

import java.net.*;
import java.io.*;
public class TCPClient
{
private static BufferedReader myReader;
private static PrintStream myOut;
private static String fileName;
private static Socket mySocket;

public static void main(String[] args) throws IOException
{
try
{
mySocket = new Socket("localhost", 6789);
myReader = new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e)
{
System.err.println("Couldn't establish a connection with server.");
System.exit(1);
}
try
{

myOut = new PrintStream(mySocket.getOutputStream());
switch (Integer.parseInt(sendOrReceive()))
{
case 1:
myOut.println("1");
sendFile();
break;
case 2:
myOut.println("2");
System.err.print("Enter file name: ");
fileName = myReader.readLine();
myOut.println(fileName);
receiveFile(fileName);
break;
}
mySocket.close();
}
catch(Exception e)
{
System.err.println("not valid input");
}
}

public static String sendOrReceive() throws IOException
{
System.out.println("1. Send file.");
System.out.println("2. Recieve file.");
System.out.print("\nMake selection: ");

return myReader.readLine();
}

public static void sendFile()
{
try
{
System.err.print("Enter file name: ");
fileName = myReader.readLine();
File myFile = new File("F:/" + fileName);
byte[] myArray = new byte[(int) myFile.length()];

FileInputStream myInFileStream = new FileInputStream(myFile);
BufferedInputStream myBufferStream = new BufferedInputStream(myInFileStream);

DataInputStream myDataIn = new DataInputStream(myBufferStream);
myDataIn.readFully(myArray, 0, myArray.length);

OutputStream myOutStream = mySocket.getOutputStream();

//Sending file name and file size to the server
DataOutputStream myDataOut = new DataOutputStream(myOutStream);
myDataOut.writeUTF(myFile.getName());
myDataOut.writeLong(myArray.length);
myDataOut.write(myArray, 0, myArray.length);
myDataOut.flush();
System.out.println("The file " + fileName + " was sent to the server.");
}
catch (Exception e)
{
System.err.println("The file " + fileName + " was not found!");
}
}

public static void receiveFile(String fileName)
{
try
{
InputStream myIn = mySocket.getInputStream();
DataInputStream myDataOut = new DataInputStream(myIn);
fileName = myDataOut.readUTF();
OutputStream myOut = new FileOutputStream(("F:/" + fileName));
long file = myDataOut.readLong();
byte[] buffer = new byte[1024];
int num = 0;
while (file > 0 && num != -1)
{
num = myDataOut.read(buffer, 0, (int) Math.min(buffer.length, file));
myOut.write(buffer, 0, num);
file -= num;
}
myOut.close();
myIn.close();
myDataOut.close();
System.out.println("The file " + fileName + " was received from the server.");
}
catch(IOException ex)
{
System.err.println("Connection closed.");
}
}
}

public class ConnectionThread implements Runnable
{
private Socket clientSocket;
private BufferedReader myBuffer = null;

public ConnectionThread(Socket aSocket)
{
this.clientSocket = aSocket;
}

@Override
public void run()
{
try
{

myBuffer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String choice = "";
while((choice = myBuffer.readLine()) != null)
{
switch (choice)
{
case "1":
receiveFile();
break;
case "2":
String fileName;
while ((fileName = myBuffer.readLine()) != null)
{
sendFile(fileName);
}
break;
default:
System.out.println("Not a valid choice. Choice must be '1' or '2'.");
break;
}
myBuffer.close();
clientSocket.close();
break;
}
}
catch(IOException e)
{
e.printStackTrace();
}
}

public void receiveFile()
{
try
{
DataInputStream myDataOut = new DataInputStream(clientSocket.getInputStream());
String fileName = myDataOut.readUTF();
FileOutputStream myOut = new FileOutputStream(("C:/SHARED/" + fileName));
long file = myDataOut.readLong();
byte[] buffer = new byte[1024];
int num = 0;
while (file > 0 && num != -1)
{
num = myDataOut.read(buffer, 0, (int) Math.min(buffer.length, file));
myOut.write(buffer, 0, num);
file -= num;
}
myOut.close();
myDataOut.close();
System.out.println("The file " + fileName + " was received from the client.");
}catch (IOException e)
{
System.err.println("Connection closed.");
}
}

public void sendFile(String fileName)
{
try
{
//handle file read
File myFile = new File("C:/Users/" + fileName);
byte[] myArray = new byte[(int) myFile.length()];

FileInputStream myInFileStream = new FileInputStream(myFile);
BufferedInputStream myInBufferStream = new BufferedInputStream(myInFileStream);

DataInputStream myDataIn = new DataInputStream(myInBufferStream);
myDataIn.readFully(myArray, 0, myArray.length);

//handle file send over socket
OutputStream myOutStream = clientSocket.getOutputStream();

//Sending file name and file size to the server
DataOutputStream myDataOut = new DataOutputStream(myOutStream);
myDataOut.writeUTF(myFile.getName());
myDataOut.writeLong(myArray.length);
myDataOut.write(myArray, 0, myArray.length);
myDataOut.flush();
System.out.println("The file " + fileName + " was sent to the client.");
}
catch(Exception e)
{
System.err.println("The file " + fileName + " was not found!");
}
}
}

最佳答案

我认为你可以在客户端的 main 中添加一个循环,正如 Saket 在评论中所说:

public static void main(String[] args) throws IOException
{
while(true) {
try
{
mySocket = new Socket("localhost", 6789);
myReader = new BufferedReader(new InputStreamReader(System.in));
}
...
...
}
}

您可以添加选项“3”来结束循环和客户端程序:

case 3:
System.exit(0);

如果您想使用单个客户端一次下载多个文件,则需要线程。

关于java - 请使用Java中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24202405/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com