java socket using byte[]
时间: 2024-01-13 09:04:46 浏览: 146
In Java, a socket can be used to establish a connection between two devices over a network. The data sent between the devices can be in the form of bytes, which are represented using a byte array.
Here is an example of a Java socket program that uses byte arrays:
```java
import java.net.*;
import java.io.*;
public class SocketExample {
public static void main(String[] args) {
try {
// Establish a connection to the server
Socket socket = new Socket("localhost", 8080);
// Create an output stream to send data to the server
OutputStream os = socket.getOutputStream();
// Create a byte array to send data
byte[] data = "Hello World!".getBytes();
// Send the data to the server
os.write(data);
// Close the output stream and socket
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
In this example, we first create a socket object and connect to a server running on the same machine (localhost) on port 8080. We then create an output stream to send data to the server.
Next, we create a byte array containing the message "Hello World!" using the `getBytes()` method. We then write this data to the output stream using the `write()` method.
Finally, we close the output stream and socket to free up resources.
This example demonstrates how to use a byte array to send data over a socket connection in Java.
阅读全文