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()
{
//初始化
//ODSocketsocket;
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(
"connecttoserversuccess!"
);
//开启新线程,在子线程中,接收数据
std::
thread
recvThread=std::
(&HelloWorld::receiveData,
this
);
recvThread.detach();
//从主线程分离
}
else
{
"cannotconnecttoserver"
);
return
;
}
}
//接收数据
HelloWorld::receiveData()
{
//因为是强联网
//所以可以一直检测服务端是否有数据传来
while
(
true
){
//接收数据Recv
data[512]=
""
;
result=socket.Recv(data,512,0);
printf
(
"%d"
(result<=0)
break
;
"%s"
//关闭连接
socket.Close();
}
//
|
24
//
public
class
Server{
static
void
main(String[]args)
throws
IOException{
//创建ServerSocket,监听端口号:12345
ServerSocketss=
new
ServerSocket(
12345
);
//创建用于管理客户端的收发数据的子线程类
ClientThreadclientThread=
ClientThread();
clientThread.start();
System.out.println(
"服务器开启啦"
);
//监听端口号:12345
//等待客户连接accept()
while
(
true
){
//开始接收客户端的连接
Socketsocket=ss.accept();
"有新客户连接~"
);
clientThread.addClient(socket);
}
}
}
2.2、ClientThread类
52
53
54
55
56
57
//继承Thread线程类
ClientThread
extends
Thread{
//客户端连接的socket列表
private
ArrayList<Socket>clients=
ArrayList<Socket>();
//添加客户
addClient(Socketsocket){
clients.add(socket);
}
//删除客户
removeClient(Socketsocket){
clients.remove(socket);
}
//向客户发送数据
sendMessage(Socketsocket,Stringdata)
IOException{
//给玩家发送数据
OutputStreamos=socket.getOutputStream();
os.write(data.getBytes(
"UTF-8"
));
}
@Override
run(){
){
try
{
for
(Socketsocket:clients){
//获取客户端发来的数据
InputStreamis=socket.getInputStream();
int
len=is.available()+
1
;
byte
[]buff=
new
[len];
flag=is.read(buff);
//read()返回-1,说明客户端的socket已断开
if
(flag==-
){
"有客户断开连接~"
);
this
.removeClient(socket);
break
;
}
//输出接收到的数据
Stringread=
String(buff);
"收到数据:"
+read);
//给玩家发送数据
Stringdata=
"恭喜你,连接成功啦~~"
;
sendMessage(socket,data);
}
sleep(
10
);
}
catch
(IOExceptione){
e.printStackTrace();
(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
3、运行服务器