我一直試圖解決這個錯誤好幾天了。真。我只是不明白。代碼很簡單..爲什麼它不工作?Java中的連接重置問題
public class server
{
public static void main(String[] args)
{
String fileName = null;
try
{
ServerSocket ss = new ServerSocket(9999, 3);
Socket dataSocket = ss.accept();
System.out.println("Server: Connection Established");
InputStream is = dataSocket.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner sc = new Scanner(dataSocket.getInputStream());
while(sc.hasNextByte())
{
System.out.println("True");
fileName = fileName+sc.next();
}
FileWriter fw = new FileWriter("server"+fileName);
while(dataSocket != null)
{
fw.write(is.read());
}
fw.flush();
dataSocket.close();
ss.close();
/*String[] nameParts;
nameParts = fileName.split(".");
File f = new File(nameParts[0]+"."+nameParts[1]);
FileOutputStream fos = new FileOutputStream(f);
System.out.println(nameParts[0]);*/
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
以上是服務器代碼。客戶端代碼如下:
public class client
{
public static void main(String[] args)
{
// Read a file
try
{
Socket dataSocket = new Socket();
dataSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
System.out.println("Client: Connection Established");
OutputStream os = dataSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String fileName = "text.txt";
pw.write(fileName);
File f = new File(fileName);
Scanner sc = new Scanner(f);
/*while(sc.hasNextInt())
{
pw.write(sc.nextInt());
}*/
//pw.flush();
//pw.close();
//dataSocket.close();
/*String[] nameParts = new String[2];
nameParts = args[0].split(".");
while(sc.hasNextByte())
{
os.write(sc.nextByte());5
}*/
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
起初,客戶端和服務器都在等待對方說話,就像兩個害羞的青少年一樣。經過一些改變,這開始發生。我收到連接重置錯誤。請幫忙。截止日期!
沒有辦法做到這一點,而不先發送名稱大小?我確定有一些方法:s這是JAVA不是C:D – Asim 2012-04-25 17:56:05
@Asim當然還有其他方法。例如,您可以使用'DataOutputStream.writeUTF()'和'DataInputStream.readUTF()'作爲文件名。 – EJP 2012-04-26 01:20:44