-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClient.java
More file actions
68 lines (57 loc) · 2.14 KB
/
Client.java
File metadata and controls
68 lines (57 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.example.nio.selector;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
/**
* Created by guolei on 16-8-7.
* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
* | 没有神兽,风骚依旧! |
* | QQ:1120832563 |
* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
*/
public class Client {
public static void main(String[] args){
try {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("192.168.0.114",3333));
ArrayList<String> messages = new ArrayList<String>();
messages.add("hello");
messages.add("world");
messages.add("my name");
messages.add("quanshijie");
messages.add("end");
for (String message : messages) {
byte[] b = new String(message).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(b);
socketChannel.write(buffer);
buffer.clear();
Thread.sleep(3000);
}
new Thread(new ReadWork(socketChannel)).start();
} catch (Exception e) {
e.printStackTrace();
}
}
static class ReadWork implements Runnable{
SocketChannel socketChannel;
public ReadWork(SocketChannel socketChannel){
this.socketChannel = socketChannel;
}
@Override
public void run() {
while (true){
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true){
try {
while (socketChannel.read(buffer) != -1){
System.err.println("啊哈,我收到服务端的消息---->"+new String(buffer.array()).trim());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}