如何防止此服务器在客户端发送文件(多线程java套接字)后接收空输出
运行程序的屏幕截图(服务器在左侧,客户端在右侧) 上述屏幕截图的问题是左侧窗口(服务器)输出“null”,而不是执行此行的正确输出:如何防止此服务器在客户端发送文件(多线程java套接字)后接收空输出,java,multithreading,sockets,Java,Multithreading,Sockets,运行程序的屏幕截图(服务器在左侧,客户端在右侧) 上述屏幕截图的问题是左侧窗口(服务器)输出“null”,而不是执行此行的正确输出:System.out.println(“文件”+filename+“下载”(+current+“字节读取”) 文件传输通信的流程如下所示: 服务器用户键入“f”,服务器按enter键,服务器键入文件名(在本例中为test.txt),服务器按enter键,客户端接收文件名,客户端向服务器发送文件,服务器接收文件,服务器输出打印行 我的问题是:我可以对以下代码进行哪些
System.out.println(“文件”+filename+“下载”(+current+“字节读取”)代码>
文件传输通信的流程如下所示:
服务器用户键入“f”,服务器按enter键,服务器键入文件名(在本例中为test.txt
),服务器按enter键,客户端接收文件名,客户端向服务器发送文件,服务器接收文件,服务器输出打印行
我的问题是:我可以对以下代码进行哪些更改,以便它为该打印行执行正确的输出
下面是在服务器端接收它的代码
public void SendFileName() throws FileNotFoundException
{
try
{
//Send the message to the client
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println("What file do you want?");
line= input.readLine();
newmessage += line + " ";
String filename = newmessage;
bw.write("filenameistotheright->` " + filename);
bw.newLine();
bw.flush();
int maxsize = 9999;
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
// receive file
byte [] mybytearray = new byte [maxsize];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(filename);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
while(bytesRead > -1)
{
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0)
{
current += bytesRead;
}
}
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + filename + " downloaded (" + current + " bytes read)");
StandardInput();
// runClientRead(clientArgs);
}
catch (IOException e)
{
e.printStackTrace();
}
}
下面是在客户端发送它的代码
import java.io.*;
import java.net.Socket;
public class ClientReceive extends Thread
{
Socket clientSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
int gotPortNumber = 0;
public ClientReceive(Socket s) throws FileNotFoundException
{
//super();
clientSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String fromServer = readFromServer.readLine();
if(fromServer.contains("filenameistotheright->` ") == true)
{
String[] parts = fromServer.split(" ");
String nonsense = parts[0];
String filename = parts[1];
System.out.println("Requested filename is: " + filename);
//sending file
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
File myFile = new File(filename);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = clientSocket.getOutputStream();
System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
else
{
String a = fromServer;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println("Recieved from server: " + alphaPart +"\n");
if(fromServer.equals(null))
{
System.exit(0);
}
}
if(fromServer.equals(null))
{
System.exit(0);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
}
服务器接收线程1:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class ServerRecieve extends Thread
{
int filePortNumber = 0;
Socket servSocket;
Socket fileSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
int gotPortNumber = 0;
int once = 0;
String fileNameGlobal = "";
public ServerRecieve(Socket s) throws FileNotFoundException
{
super();
this.servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromClient = readFromClient.readLine();
if(fromClient.contains("filenameistotheright->` ") == true)
{
String[] parts = fromClient.split(" ");
final String filename = parts[1];
System.out.println("Requested filename is: " + filename);
fileNameGlobal = filename;
//Sending the file
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
File myFile = new File(filename);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = servSocket.getOutputStream();
System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
else
{
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println("Recieved from client: " + alphaPart +"\n");
if(gotPortNumber == 0)
{
String[] parts1 = fromClient.split(" ");
String nonsense1 = parts1[0];
String filename1 = parts1[1];
System.out.println("File transfer port found: " + numberPart + "\n");
gotPortNumber = 3;
filePortNumber = Integer.parseInt(numberPart);
int p = 0;
p = strToInt(numberPart);
System.out.println(filename1);
//starting the recieving thread
if(once == 0)
{
String[] parts12 = fromClient.split(" ");
String nonsense12 = parts12[0];
String filename31 = parts12[1];
//System.out.println("name:" + filename31);
String address = "localhost";
// fileSocket = new Socket(address, p);
//ServerSocket serverSocket1 = new ServerSocket(p);
if((filename31.equals(null) == true) && (!filename31.equals("")==true))
{
ServerFile getServerFile = new ServerFile(servSocket, p, filename31);
getServerFile.start();
}
once = 4;
}
once = 4;
}
gotPortNumber = 3;
if(fromClient.equals(null))
{
System.exit(0);
}
OutputOptions();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public int strToInt( String str )
{
int i = 0;
int num = 0;
boolean isNeg = false;
//Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
//Process each character of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
}
具有完整上下文的客户端代码:
您有一个例外
您的服务器文件中有一个pokemon catch(catch(异常e)
,即“catch all”)。pokemon catch只打印异常消息,而不是堆栈跟踪。异常的消息可以为null,这就是您看到的null
现在,那是从哪里来的?嗯,你有:
Socket sock = null;
// receive file
byte [] mybytearray = new byte [maxsize];
InputStream is = sock.getInputStream();
如果sock
为null
,则无法获取sock.getInputStream()
。您会得到一个NullPointerException
。这在你的《抓住他们》中被抓住了,它可能没有任何信息
- 避免被口袋妖怪抓到
- 始终打印堆栈跟踪,而不是消息
- 给你的
sock
一个实际值
谢谢,我会试试这个。这里的问题太多了。扔掉它,在我回答重复问题时使用代码。
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class ServerRecieve extends Thread
{
int filePortNumber = 0;
Socket servSocket;
Socket fileSocket;
boolean m_bRunThread = true;
boolean ServerOn = true;
int gotPortNumber = 0;
int once = 0;
String fileNameGlobal = "";
public ServerRecieve(Socket s) throws FileNotFoundException
{
super();
this.servSocket = s;
}
public void run()
{
while(true)
{
try
{
BufferedReader readFromClient = new BufferedReader(new InputStreamReader(servSocket.getInputStream()));
String fromClient = readFromClient.readLine();
if(fromClient.contains("filenameistotheright->` ") == true)
{
String[] parts = fromClient.split(" ");
final String filename = parts[1];
System.out.println("Requested filename is: " + filename);
fileNameGlobal = filename;
//Sending the file
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
File myFile = new File(filename);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = servSocket.getOutputStream();
System.out.println("Sending " + filename + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
}
else
{
String a = fromClient;
int i;
for(i = 0; i < a.length(); i++)
{
char c = a.charAt(i);
if( '0' <= c && c <= '9' )
{
break;
}
}
String alphaPart = a.substring(0, i);
String numberPart = a.substring(i);
System.out.println("Recieved from client: " + alphaPart +"\n");
if(gotPortNumber == 0)
{
String[] parts1 = fromClient.split(" ");
String nonsense1 = parts1[0];
String filename1 = parts1[1];
System.out.println("File transfer port found: " + numberPart + "\n");
gotPortNumber = 3;
filePortNumber = Integer.parseInt(numberPart);
int p = 0;
p = strToInt(numberPart);
System.out.println(filename1);
//starting the recieving thread
if(once == 0)
{
String[] parts12 = fromClient.split(" ");
String nonsense12 = parts12[0];
String filename31 = parts12[1];
//System.out.println("name:" + filename31);
String address = "localhost";
// fileSocket = new Socket(address, p);
//ServerSocket serverSocket1 = new ServerSocket(p);
if((filename31.equals(null) == true) && (!filename31.equals("")==true))
{
ServerFile getServerFile = new ServerFile(servSocket, p, filename31);
getServerFile.start();
}
once = 4;
}
once = 4;
}
gotPortNumber = 3;
if(fromClient.equals(null))
{
System.exit(0);
}
OutputOptions();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
void OutputOptions()
{
System.out.println("Enter an option ('m', 'f', 'x'): ");
System.out.println("(M)essage (send)");
System.out.println("(F)ile (request) ");
System.out.println("e(X)it ");
}
public int strToInt( String str )
{
int i = 0;
int num = 0;
boolean isNeg = false;
//Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
//Process each character of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
}
import java.net.Socket;
import java.io.*;
import java.util.*;
public class ServerFile extends Thread
{
public Socket servingSocket = null;
public int FilePort = 0;
public String otherName = "";
public ServerFile(Socket ok, int port, String FileName) throws FileNotFoundException
{
this.FilePort = port;
this.servingSocket = ok;
this.otherName = FileName;
}
public void run()
{
while(true)
{
try
{
int maxsize = 999999;
byte[] buffer = new byte[maxsize];
//servingSocket = new Socket("localhost", FilePort);
InputStream is = servingSocket.getInputStream();
File test = new File(otherName);
test.createNewFile();
FileOutputStream fos = new FileOutputStream(test);
BufferedOutputStream out = new BufferedOutputStream(fos);
int byteread = is.read(buffer, 0, buffer.length);
int current = byteread;
buffer = new byte[16384];
while ((byteread = is.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, byteread);
}
out.flush();
//socket.close();
// fos.close();
// is.close();
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
}
}
}
}
Socket sock = null;
// receive file
byte [] mybytearray = new byte [maxsize];
InputStream is = sock.getInputStream();