使用Groovy进行Socket编程之-字节数组版
时间: 2024-02-03 15:15:29 浏览: 129
使用Groovy进行Socket编程,实现字节数组版的话,可以通过以下步骤实现:
1. 创建Socket对象,指定服务器IP和端口号。
```groovy
def socket = new Socket("127.0.0.1", 8888)
```
2. 获取输入输出流。
```groovy
def inputStream = socket.getInputStream()
def outputStream = socket.getOutputStream()
```
3. 发送字节数组数据。
```groovy
def data = "Hello World".getBytes()
outputStream.write(data)
```
4. 接收字节数组数据。
```groovy
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
def receivedData = new String(buffer, 0, len);
```
5. 关闭Socket连接。
```groovy
socket.close()
```
完整代码示例:
```groovy
import java.net.Socket
def socket = new Socket("127.0.0.1", 8888)
def inputStream = socket.getInputStream()
def outputStream = socket.getOutputStream()
def data = "Hello World".getBytes()
outputStream.write(data)
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
def receivedData = new String(buffer, 0, len);
println "Received data: $receivedData"
socket.close()
```