Cocos网络篇[3.2](3) ——Socket连接(1)
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
|
// // 引入头文件 #include "ODSocket/ODSocket.h" // Socker连接 void HelloWorld::connectServer() { // 初始化 // ODSocket socket; socket.Init(); socket.Create(AF_INET, SOCK_STREAM, 0); // 设置服务器的IP地址,端口号 // 并连接服务器 Connect const char * ip = "127.0.0.1" ; int port = 12345; bool result = socket.Connect(ip, port); // 发送数据 Send socket.Send( "login" , 5); if (result) { CCLOG( "connect to server success!" ); // 开启新线程,在子线程中,接收数据 std:: thread recvThread = std:: thread (&HelloWorld::receiveData, this ); recvThread.detach(); // 从主线程分离 } else { CCLOG( "can not connect to server" ); return ; } } // 接收数据 void HelloWorld::receiveData() { // 因为是强联网 // 所以可以一直检测服务端是否有数据传来 while ( true ) { // 接收数据 Recv char data[512] = "" ; int result = socket.Recv(data, 512, 0); printf ( "%d" , result); // 与服务器的连接断开了 if (result <= 0) break ; CCLOG( "%s" , data); } // 关闭连接 socket.Close(); } // |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
// public class Server { public static void main(String[] args) throws IOException { // 创建ServerSocket,监听端口号:12345 ServerSocket ss = new ServerSocket( 12345 ); // 创建用于管理客户端的收发数据的子线程类 ClientThread clientThread = new ClientThread(); clientThread.start(); System.out.println( "服务器开启啦" ); // 监听端口号:12345 // 等待客户连接 accept() while ( true ) { // 开始接收客户端的连接 Socket socket = ss.accept(); System.out.println( "有新客户连接~" ); clientThread.addClient(socket); } } } // |
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
|
// // 继承Thread线程类 public class ClientThread extends Thread { // 客户端连接的socket列表 private ArrayList<Socket> clients = new ArrayList<Socket>(); // 添加客户 public void addClient(Socket socket) { clients.add(socket); } // 删除客户 public void removeClient(Socket socket) { clients.remove(socket); } // 向客户发送数据 public void sendMessage(Socket socket, String data) throws IOException { // 给玩家发送数据 OutputStream os = socket.getOutputStream(); os.write(data.getBytes( "UTF-8" )); } @Override public void run() { while ( true ) { try { for (Socket socket : clients) { // 获取客户端发来的数据 InputStream is = socket.getInputStream(); int len = is.available() + 1 ; byte [] buff = new byte [len]; int flag = is.read(buff); // read()返回-1,说明客户端的socket已断开 if (flag == - 1 ) { System.out.println( "有客户断开连接~" ); this .removeClient(socket); break ; } // 输出接收到的数据 String read = new String(buff); System.out.println( "收到数据:" + read); // 给玩家发送数据 String data = "恭喜你,连接成功啦~~" ; sendMessage(socket, data); } sleep( 10 ); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } } // |