有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么不能用socket发送正确的数据?JAVA(在本地计算机上运行的ClientServer程序)

我正在尝试用java编写一个服务器-客户机程序。我试着在同一个系统上运行。它将一个文本文件从客户端发送到服务器,包括名称等。但当服务器收到该文件时,它只打印“[]”字符。这是指空值还是指数据损坏

这是服务器

package temel;

import java.io.File;
import java.io.InputStream;
import java.net.Socket;
import java.net.ServerSocket;

public class VeriAlma {

  private static int port;

  private static Socket socket;
  public VeriAlma(int port)
  {
      VeriAlma.port=port;
  }
  public static void veriAl() {
    try {
        ServerSocket listener = new ServerSocket(port);

                socket = listener.accept(); 

    }
    catch (java.lang.Exception ex) {
      ex.printStackTrace(System.out);
    }
  }

  public String run() {
    try {
      InputStream in = socket.getInputStream();


        String file_name = "x.txt";

        File file=new File(file_name);

        ByteStream.toFile(in, file);
      return file_name;
    }
    catch (java.lang.Exception ex) {
      ex.printStackTrace(System.out);
      return "asdasd";
    }
  }
  public void setPort(int port)
  {
      VeriAlma.port=port;

  }
}

这是客户

package temel;
import java.io.*;
import java.net.*;
import java.lang.*;

import java.io.OutputStream;
import java.io.InputStream;
import java.io.File;
import java.io.FileOutputStream;

import java.net.Socket;

public class VeriGonderme {

      // host and port of receiver
      private static int    port;
      private static String host;

      public VeriGonderme(int port,String host)
      {
          this.port=port;
          this.host=host;
      }
      public void veriGonder(String dosyaIsmi) {
        try {
          Socket       socket = new Socket(host, port);
          OutputStream os     = socket.getOutputStream();


          ByteStream.toStream(os, 1);


            ByteStream.toStream(os, dosyaIsmi);
            ByteStream.toStream(os, new File(dosyaIsmi));
          }catch (Exception ex) {
          ex.printStackTrace();
        }
        }
      public void setPort(int port)
      {
          this.port=port;

      }
      public void setHost(String host)
      {
          this.host=host;

      }

      }

主机为“localhost”,端口为4444

This is the original code i modified it a little bit


共 (1) 个答案

  1. # 1 楼答案

    But when the server gets the file it just prints "[]" characters.

    我希望看到一些这样的字符,因为您将值1作为4字节二进制文件发送。i、 e.\0\0\0\u0001如果您删除此文件并只发送一次文件,它可能会按照您的预期执行