因此,我正在尝试编写代码以实现通过客户端和服务器在Java中以字节为单位逐个字节发送的图像。 This is the jist of the assignment
这是服务器的代码:
import java.io.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class UDPServer {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876); //makes the datagram socket at the port 9876 for dat transfer
byte[] receiveData = new byte[1024]; //allocate memory for data being recieved
byte[] sendData = new byte[1024]; //allocate memory for data being sent
byte[] buffer = new byte[1024];
DatagramPacket receiveByte = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receiveByte);
byte[] data = receiveByte.getData();
ByteArrayInputStream bais = new ByteArrayInputStream(data);
BufferedImage image2 = ImageIO.read(bais);
ImageIO.write(image2, "bmp", new File("C:\\Users\\Demon FFA\\Documents\\Network Design\\Phase 2\\word1.bmp"));
System.out.println("Image receieved!");
以下是客户端代码:
import java.io.*;
import java.net.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); //create input stream for client to server message
DatagramSocket clientSocket = new DatagramSocket(); //create the socket for the client
InetAddress IPAddress = InetAddress.getByName("localhost"); //change the hostname into an ip address with DNS
byte[] sendData = new byte[1024]; //allocate memory for data being sent
byte[] receiveData = new byte[1024]; //allocate memory for the data being recieved
BufferedImage image = ImageIO.read(new File("C:\\Users\\Demon FFA\\Documents\\Network Design\\Phase 2\\word.bmp"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "bmp", baos);
//baos.flush();
byte[] data = baos.toByteArray();
byte[] buffer = new byte[1024];
int i;
int c = 0;
for(i = 0; i<data.length; i++) {
buffer[c] = data[i];
c++;
if (i%1024==0){
c = 0;
}
DatagramPacket sendByte = new DatagramPacket(buffer, buffer.length, IPAddress, 9876);
clientSocket.send(sendByte);
}
}
}
这是错误: