Libgdx: android单机斗地主支持局域网wifi联网的网络模块核心代码
这个作品是我近期写的,结合我的毕业设计的通信模块和之前的单机版斗地主。我已经上架到豌豆荚了,贴了点广告,看看能不能赚点茶钱。
但是一点也不乐观。因此我想分享给大家源代码。
仅仅要不用于商业。
以下先贴网络模块的核心代码,第一次写这样的逻辑用的udp, 经验不够,没有写的那么好看。
这里是我上架的apk,大家下载来试试也无妨: 地址 http://www.wandoujia.com/apps/com.hj.joker
package com.hj.net; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.Vector; import org.apache.http.conn.util.InetAddressUtils;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.hj.screen.NetGameScreen;
import com.hj.screen.RommScreen;
import com.hj.tool.Card;
import com.hj.tool.Comm; import android.os.Message;
import android.util.Log; public class NetManager { // 初始化
public RommScreen rommScreen = null;
public NetGameScreen netGameScreen = null;
public static int Max = 3;
public User me = null, u = null, computer = null;
public List<User> users = null;
public Room currentRoom = null;
public List<Room> roomList = null;// 本主机的全部用户
public boolean isStop = true;
public boolean LeaveRoom = false;
public CardData cards[] = new CardData[56];
public List<CardData> cardDataList = new ArrayList<CardData>();
// 协议命令
public static final int CMD_HOST_REQUEST_ROOM = 10;
public static final int CMD_REPLY_ROOM = 11;
public static final int CMD_CREATE_ROOM = 12;
public static final int MES_UPDATE_ROOM = 13;
public static final int MES_UPDATE_User = 14;
public static final int CMD_HOST_JOIN_ROOM = 15;
public static final int CMD_BROAD_USERLIST = 16;
public static final int CMD_UPDATE_ROOM = 17;
public static final int CMD_HOST_LEAVE_ROOM = 18;
public static final int CMD_LEAVE_ROOM = 19;
public static final int CMD_DEL_ROOM = 20;
public static final int CMD_HOST_READY_ROOM = 21;
public static final int CMD_BEGIN_CARDS = 22;
public static final int MES_UPDATE_BEGINCARD = 23;
public static final int MES_UPDATE_LANDLORD = 24;
public static final int CMD_HOST_FINISH_LANDLORD = 25;
public static final int CMD_BROAD_NEXT_LANDLORD = 26;
public static final int CMD_BEGIN_LANDLORD_CARDS = 27;
public static final int CMD_HOST_START_CARDS = 28;
public static final int CMD_START_CARDS = 29;
public static final int MES_SHOW_CARDBUTTON = 30;
public static final int MES_UPDATE_LANDLORDHEAD = 31;
public static final int CMD_HOST_SEND_CARDS = 32;
public static final int CMD_SEND_CARDS = 33;
public static final int MES_SEND_CARDS = 34;
public static final int CMD_SEND_CURRENTID_CARDS = 35;
public static final int MES_FLUSH_CARDS = 36;
public static final int CMD_HOST_SEND_CARDS_COMPUTER = 37;
public static final int PORT_SEND = 2429;// 发送端口
public static final int PORT_RECEIVE = 2425;// 接收端口 public NetManager() {
roomList = new ArrayList<Room>();
users = new ArrayList<User>();
} public void init() {
users.clear();
cardDataList.clear();
for (int i = 0; i < 3; i++) {
netGameScreen.gInfo.playerList[i].clear();
netGameScreen.gInfo.playerOutList[i].clear();
}
netGameScreen.gInfo.playerList[3].clear();
// users
} // 发送消息
public void sendCMD(Msg msg) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
(new UdpSend(msg)).start();
} class UdpSend extends Thread {
Msg msg = null; UdpSend(Msg msg) {
this.msg = msg;
} public void run() {
try {
byte[] data = toByteArray(msg);
DatagramSocket ds = new DatagramSocket(PORT_SEND + Max);
DatagramPacket packet = new DatagramPacket(data, data.length,
InetAddress.getByName(msg.getReceiveUserIp()),
PORT_RECEIVE + Max);
packet.setData(data);
ds.send(packet);
ds.close();
} catch (Exception e) {
} }
} // 接收消息
public void openReceiveMsgThread() {
(new UdpReceive()).start();
} public class UdpReceive extends Thread {
Msg msg = null; UdpReceive() {
} public void run() {
// 消息循环
while (!isStop) {
try {
DatagramSocket ds = new DatagramSocket(PORT_RECEIVE + Max);
byte[] data = new byte[1024 * 32];
DatagramPacket dp = new DatagramPacket(data, data.length);
dp.setData(data);
ds.receive(dp);
byte[] data2 = new byte[dp.getLength()];
System.arraycopy(data, 0, data2, 0, data2.length);// 得到接收的数据
Msg msg = (Msg) toObject(data2);
ds.close(); // 解析消息
parse(msg);
} catch (Exception e) {
}
} }
} // 解析接收的
public void parse(Msg msg) {
Room r = null;
switch (msg.getMsgType()) {
case CMD_HOST_REQUEST_ROOM:// 搜索桌子
u = (User) msg.getBody();
if (me.getIp().equals(currentRoom.getIp())) {
// out("有人进房间:"+u.getIp());
replyRoom(u);
}
break;
case CMD_REPLY_ROOM: // 收到反馈桌子
r = (Room) msg.getBody();
if (!isContainsRoom(r)) {
roomList.add(r);
updateRoomList();
}
break;
case CMD_CREATE_ROOM: // 收到创建的桌子
r = (Room) msg.getBody();
if (!isContainsRoom(r)) {
roomList.add(r);
updateRoomList();
}
break;
case CMD_HOST_JOIN_ROOM: // 收到请求增加桌子
u = (User) msg.getBody();
// out("收到请求");
if (!isContainsUser(u)) {
users.add(u);
currentRoom.userCount++;
orderComputer();
broadUser();
// 反馈桌子人数更新
updateRoom();
}
break;
case CMD_UPDATE_ROOM: // 收到桌子列表更新
r = (Room) msg.getBody();
if (isContainsRoom(r)) {
for (Room t : roomList) {
if (t.getIp().equals(r.getIp()))
t.setUserCount(r.getUserCount());
}
} else
roomList.add(r);
updateRoomList();
break;
case CMD_BROAD_USERLIST:// 收到用户列表更新
// out("收到广播");
users = (ArrayList) msg.getBody();
updateUserList();
break;
case CMD_HOST_LEAVE_ROOM: // 主机离开房间
u = (User) msg.getBody();
leaveRoom2(u);
break;
case CMD_DEL_ROOM: // 收到删除房间
r = (Room) msg.getBody();
if (isContainsRoom(r)) {
removeRoom(r);
}
updateRoomList();
break;
case CMD_LEAVE_ROOM:
u = (User) msg.getBody();
if (!u.getIp().equals(me.getIp())) {
LeaveRoom = true;
init();
users.clear();
currentRoom = null;
updateRoomList();
}
break;
case CMD_HOST_READY_ROOM: // 准备
u = (User) msg.getBody();
for (User user : users) {
if (user.getIp().equals(u.getIp()))
user.setReady(true);
}
// broadUser();
// 開始游戏
beginGame();
break;
case CMD_BEGIN_CARDS:// 收到发的牌0
cardDataList.clear();
cardDataList = (ArrayList<CardData>) msg.getBody();
updateBeginCard();
startLandlord();
break; case CMD_BROAD_NEXT_LANDLORD: // 被通知显示抢分button
updateLandlord(1);
break;
case CMD_HOST_FINISH_LANDLORD: // 按下了抢分button
u = (User) msg.getBody();
// out("fenfen");
// out("分:"+u.getLandlordScore());
// out("id:"+u.getDeskId());
// 推断抢分完毕没有
if (!judgeFinishLandlord())
nextLandlord(u.getDeskId());
break;
case CMD_BEGIN_LANDLORD_CARDS: // 收到地主牌
cardDataList.clear();
cardDataList = (ArrayList<CardData>) msg.getBody();
netGameScreen.gInfo.setLandlordId(cardDataList.get(0).deskId);
updateBeginCard();
updateLandLordHead();
break;
case CMD_HOST_START_CARDS: // 谁是地主
sendCMD(new Msg(me.getName(), me.getIp(), null,
(String) msg.getBody(), CMD_START_CARDS, null));
break;
case CMD_START_CARDS: // 地主開始出牌
showCardButton();
break;
case CMD_HOST_SEND_CARDS: // 有人出牌了 int desk = -1;
for (User s : users) {
if (s.getIp().equals(msg.getSendUserIp()))
desk = s.getDeskId();
}
out(desk + ":出牌");
// sendID
for (User user : users) {
if (Max == 3 || (!user.getIp().equals("null"))) {
if (!user.getIp().equals(currentRoom.getIp()))
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_SEND_CURRENTID_CARDS,
(desk + 1) % 3));
}
}
netGameScreen.gInfo.setCurrentPlayerId((desk + 1) % 3);
cardDataList.clear();
cardDataList = (ArrayList<CardData>) msg.getBody();
for (CardData cd : cardDataList)
out("出了:" + cd.imageId);
// 将牌分给组内人
for (User user : users) {
if (Max == 3 || (!user.getIp().equals("null"))) {
if (!user.getIp().equals(currentRoom.getIp())) {
sleepT(300);
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_SEND_CARDS, new ArrayList(
cardDataList)));
// out("给:"+user.getDeskId()+":size:"+cardDataList.size());
}
}
}
updateCards(desk);
// 下一个人
if (!(Max == 2 && desk == 1)) {
// out("下一个人");
sendCMD(new Msg(me.getName(), me.getIp(), null,
currentRoom.getIp(), CMD_HOST_START_CARDS, users.get(
(desk + 1) % 3).getIp()));
}
// Computer出牌
if (Max == 2 && netGameScreen.gInfo.getCurrentPlayerId() == 2) {
// 电脑出牌
out("电脑出牌");
sleepT(1000);
cardDataList.clear();
netGameScreen.gInfo.playerOutList[2] = Comm.getBestAI(
netGameScreen.gInfo.playerList[2],
netGameScreen.gInfo.getOppo());
if (netGameScreen.gInfo.playerOutList[2] == null)
out("电脑没牌出");
else {
out("电脑出的牌:" + netGameScreen.gInfo.playerOutList[2].size());
String s = "";
for (Card cd : netGameScreen.gInfo.playerOutList[2]) {
s += cd.value + ",";
cardDataList.add(new CardData(cd.imageId, 2));
}
out("电脑牌:" + s);
}
sendCMD(new Msg(me.getName(), me.getIp(), null,
currentRoom.getIp(), CMD_HOST_SEND_CARDS_COMPUTER,
cardDataList));
}
break;
case CMD_HOST_SEND_CARDS_COMPUTER: // 电脑接收
out("电脑出牌来接收");
// sendID
for (User user : users) {
if (Max == 3 || (!user.getIp().equals("null"))) {
if (!user.getIp().equals(currentRoom.getIp()))
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_SEND_CURRENTID_CARDS,
(2 + 1) % 3));
}
}
netGameScreen.gInfo.setCurrentPlayerId((2 + 1) % 3);
cardDataList.clear();
cardDataList = (ArrayList<CardData>) msg.getBody();
// out("cc");
// 将牌分给组内人
for (User user : users) {
if (Max == 3 || (!user.getIp().equals("null"))) {
if (!user.getIp().equals(currentRoom.getIp())) {
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_SEND_CARDS, cardDataList));
// out("向发送了牌:"+user.getDeskId());
}
}
}
// out("bb");
updateCards(2);
// out("电脑出了牌");
// 下一个人
sendCMD(new Msg(me.getName(), me.getIp(), null,
currentRoom.getIp(), CMD_HOST_START_CARDS, users.get(
(2 + 1) % 3).getIp())); break;
case CMD_SEND_CARDS: // 收到广播来的牌
int desk1 = -1;
while (desk1 < 0) {
desk1 = (netGameScreen.gInfo.getCurrentPlayerId() + 2) % 3;
}
// out("出牌的人"+desk1);
cardDataList.clear();
cardDataList = (ArrayList<CardData>) msg.getBody();
out("xx:" + cardDataList.size());
updateCards(desk1);
break;
case CMD_SEND_CURRENTID_CARDS: // 收到当前ID
netGameScreen.gInfo.setCurrentPlayerId((Integer) msg.getBody());
break;
}
} // ***********************************************游戏逻辑**************************************************
// AI
public void orderComputer() {
if (Max == 2) {
User t1 = users.get(1), t2 = users.get(2);
;
users.remove(t1);
users.remove(t2);
users.add(t2);
users.add(t1);
} } public void addComputer() {
if (Max == 2) {
// out("addCPU");
computer = new User("computer", "null");
computer.setDeskId(2);
computer.setReady(true);
users.add(computer);
}
} // NET
public void requestRoom() {
// out("port:"+Max);
roomList.clear();
sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
CMD_HOST_REQUEST_ROOM, me));
} public void replyRoom(User user) {
// out("sendCMD:CMD_REPLY_ROOM");
sendCMD(new Msg(me.getName(), me.getIp(), null, user.getIp(),
CMD_REPLY_ROOM, currentRoom)); } public void createRoom() {
// 增加自己当user
me.setDeskId(users.size());
users.add(me);
addComputer();
// out("currentSize:"+users.size());
currentRoom = new Room(me.getIp(), 1);
roomList.add(currentRoom);
sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
CMD_CREATE_ROOM, currentRoom));
updateUserList(); } public void joinRoom(Room r) {
// out("申请增加:"+r.getIp()+",人数已有:"+r.getUserCount() );
currentRoom = r;
me.setDeskId(r.userCount);
sendCMD(new Msg(me.getName(), me.getIp(), null, r.getIp(),
CMD_HOST_JOIN_ROOM, me));
} public void updateRoom() {
// out("sendCMD:CMD_UPDATE_ROOM");
sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
CMD_UPDATE_ROOM, currentRoom));
} public void broadUser() {
// /out("sendCMD:CMD_BROAD_USERLIST");
for (User user : users) {
// out("广播:"+user.getIp());
if (Max == 3 || (!user.getIp().equals("null")))
sendCMD(new Msg(me.getName(), me.getIp(), null, user.getIp(),
CMD_BROAD_USERLIST, users));
}
updateUserList();
} public void leaveRoom1() {
// out("leaveIp:"+me.getIp()+",HostIP:"+currentRoom.getIp());
sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
CMD_HOST_LEAVE_ROOM, me));
} public void leaveRoom2(User u) {
// out("2leaveIp:"+u.getIp()+",HostIP:"+currentRoom.getIp());
if (currentRoom.getIp().equals(u.getIp())
|| netGameScreen.gInfo.playerList[0].size() > 0) {
// 解散桌子
for (User user : users) {
if (Max == 3 || (!user.getIp().equals("null")))
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_LEAVE_ROOM, me));
}
init();
delRoom(currentRoom);
removeRoom(currentRoom);
LeaveRoom = true;
users.clear();
currentRoom = null;
updateRoomList();
} else {
removeUser(u);
currentRoom.userCount--;
updateRoom();
broadUser();
sendCMD(new Msg(me.getName(), me.getIp(), null, u.getIp(),
CMD_LEAVE_ROOM, null));
}
} public void delRoom(Room r) {
sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
CMD_DEL_ROOM, r));
} public void getReady() {
me.setReady(true);
sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
CMD_HOST_READY_ROOM, me));
} public void beginGame() {
int count = 0;
for (User user : users) {
if (user.isReady()) {
count++;
}
}
if (count == 3) {
// out("准备完毕:開始发牌");
// 取消准备图标
for (User user : users) {
user.setReady(false);
}
broadUser();
cardDataList.clear();
int len = 54;
for (int i = 1; i <= len; i++)
cards[i] = new CardData(i, -1);
// out("洗牌");
// 洗牌
for (int i = 0; i < 100; i++) {
Random random = new Random();
int a = random.nextInt(54) + 1;
int b = random.nextInt(54) + 1;
CardData k = cards[a];
cards[a] = cards[b];
cards[b] = k;
}
// out("发牌");
// 发牌
for (int i = 1; i <= 51; i++) {
cardDataList.add(cards[i]);
cards[i].setDeskId(i % 3);
}
// out("地主牌");
// 地主牌
for (int i = 52; i <= 54; i++) {
cardDataList.add(cards[i]);
cards[i].setDeskId(3);
}
// 将牌分给组内人
for (User user : users) {
// out("ip:"+user.getIp());
if (Max == 3 || (!user.getIp().equals("null"))) {
if (!user.getIp().equals(currentRoom.getIp()))
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_BEGIN_CARDS, cardDataList));
}
}
// out(cardDataList.size()+":ab");
updateBeginCard();
startLandlord();
} else
broadUser();
} public void startLandlord() {
if (me.getIp().equals(currentRoom.getIp())) {// 房主确定谁是地主
netGameScreen.gInfo.FirstLandLordId = 0;// 房主先抢地主
netGameScreen.gInfo
.setCurrentPlayerId(netGameScreen.gInfo.FirstLandLordId);
updateLandlord(1);
}
} public void finishLandlord() {
sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
CMD_HOST_FINISH_LANDLORD, me));
} public void nextLandlord(int deskId) {
// out("通知下一个抢地主:"+users.get((deskId+1)%3).getIp());
sendCMD(new Msg(me.getName(), me.getIp(), null, users.get(
(deskId + 1) % 3).getIp(), CMD_BROAD_NEXT_LANDLORD, null));
} public boolean judgeFinishLandlord() {
int count = 0;
User maxUser;
for (User user : users) {
if (user.getLandlordScore() > -1)
count++;
}
if (count == 3) {
// out("完毕抢分");
int landlordId = Comm.getLandOwnerId(new int[] {
users.get(0).getLandlordScore(),
users.get(1).getLandlordScore(),
users.get(2).getLandlordScore() }, 0);
// out("地主ID:"+landlordId);
netGameScreen.gInfo.LandlordId = landlordId;
for (User user : users) {
user.setLandlordScore(-1);
// out("设置:"+user.getIp()+":取消分数显示");
}
broadUser();
// 将地主牌送入地主
cardDataList.clear();
for (Card c : netGameScreen.gInfo.playerList[3]) {
cardDataList.add(new CardData(c.imageId, landlordId));
}
// 将牌分给组内人
for (User user : users) {
// out("发牌给:"+user.getIp());
if (Max == 3 || (!user.getIp().equals("null"))) {
if (!user.getIp().equals(currentRoom.getIp()))
sendCMD(new Msg(me.getName(), me.getIp(), null,
user.getIp(), CMD_BEGIN_LANDLORD_CARDS,
cardDataList));
}
}
// 由于自己不须要再发一遍给自己
updateBeginCard();
updateLandLordHead();
broadUser();
// 通知地主出牌
startHostCard();
return true;
}
return false;
} public void startHostCard() {
// out("地主ID:"+users.get(netGameScreen.gInfo.LandlordId).getIp());
sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
CMD_HOST_START_CARDS, users.get(netGameScreen.gInfo.LandlordId)
.getIp()));
} public void sendHostCards() {
// out("通知Host出牌了");
cardDataList.clear();
for (Card cd : netGameScreen.gInfo.playerOutList[me.getDeskId()]) {
// out("取2:"+cd.imageId);
cardDataList.add(new CardData(cd.imageId, me.getDeskId()));
} sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
CMD_HOST_SEND_CARDS, cardDataList));
} // UI
void flush(List<Card> list) {
sendMes2(MES_FLUSH_CARDS, list);
} void updateCards(int desk) { flush(netGameScreen.gInfo.playerOutList[(desk + 1) % 3]);
if (netGameScreen.gInfo.playerOutList[desk] != null)
netGameScreen.gInfo.playerOutList[desk].clear();
for (Card c1 : netGameScreen.gInfo.playerList[desk]) {
for (CardData card : cardDataList) {
if (card.imageId == c1.imageId) {
netGameScreen.gInfo.playerOutList[desk].add(c1);
}
}
}
if (netGameScreen.gInfo.playerOutList[desk] != null)
netGameScreen.gInfo.playerList[desk]
.removeAll(netGameScreen.gInfo.playerOutList[desk]);
// 发牌
sendMes2(MES_SEND_CARDS, desk);
} void updateLandLordHead() {
sendMes2(MES_UPDATE_LANDLORDHEAD, null);
} void showCardButton() {
// out("显示出牌button");
sendMes2(MES_SHOW_CARDBUTTON, null);
} void updateLandlord(int visible) {
sendMes2(MES_UPDATE_LANDLORD, visible);
} void updateBeginCard() {
// out(cardDataList.size()+":a");
for (CardData card : cardDataList) {
Card cards = new Card(card.getImageId(), netGameScreen.atlsa);
netGameScreen.gInfo.playerList[card.getDeskId()].add(cards);
// netGameScreen.net.out(card.getDeskId()+":"+me.getDeskId());
if (card.getDeskId() == me.getDeskId()) {
cards.addListener(new ClickListener() {
@Override
public boolean touchDown(InputEvent event, float x,
float y, int pointer, int button) {
Card c = (Card) event.getListenerActor();
if(netGameScreen.gInfo.getGameState()==2)
c.move();
c.touched=1;
Log.v("test", "touch" + c.imageId);
return super.touchDown(event, x, y, pointer, button);
} });
}
}
// 发牌
sendMes2(MES_UPDATE_BEGINCARD, null);
} void updateRoomList() {
sendMes1(MES_UPDATE_ROOM, null);
} void updateUserList() {
sendMes2(MES_UPDATE_User, null);
} // ***********************************************功能函数*************************************************
public boolean isContainsRoom(Room r) {
for (int i = 0; i < roomList.size(); i++) {
if (roomList.get(i).getIp().equals(r.getIp()))
return true;
}
return false;
} public boolean isContainsUser(User u) {
for (int i = 0; i < users.size(); i++) {
// out(users.get(i).getIp()+":"+u.getIp());
if (users.get(i).getIp().equals(u.getIp())) {
return true;
}
// out("lala");
}
// out("false");
return false;
} public void removeRoom(Room room) { Room t = null;
for (Room r : roomList) {
if (r.getIp().equals(room.getIp()))
t = r;
}
roomList.remove(t);
} public void removeUser(User user) {
User t = null;
for (User r : users) {
if (r.getIp().equals(user.getIp()))
t = r;
}
users.remove(t);
} // 发送Handle
public void sendMes1(int cmd, Object o) {
Message m = new Message();
m.what = cmd;
m.obj = o;
if (rommScreen != null)
rommScreen.handler.sendMessage(m); } public void sendMes2(int cmd, Object o) {
Message m = new Message();
m.what = cmd;
m.obj = o;
if (netGameScreen != null)
netGameScreen.handler.sendMessage(m);
} // 获取当前时间
public static long getTimel() {
return System.currentTimeMillis();
} // 得到广播ip, 192.168.0.255之类的格式
public String getBroadCastIP() {
String ip = getLocalHostIp().substring(0,
getLocalHostIp().lastIndexOf(".") + 1)
+ "255";
return ip;
} // 获取本机IP
public String getLocalHostIp() {
String ipaddress = "";
try {
Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces();
// 遍历所用的网络接口
while (en.hasMoreElements()) {
NetworkInterface nif = en.nextElement();// 得到每个网络接口绑定的全部ip
Enumeration<InetAddress> inet = nif.getInetAddresses();
// 遍历每个接口绑定的全部ip
while (inet.hasMoreElements()) {
InetAddress ip = inet.nextElement();
if (!ip.isLoopbackAddress()
&& InetAddressUtils.isIPv4Address(ip
.getHostAddress())) {
return ipaddress = ip.getHostAddress();
}
} }
} catch (SocketException e) {
System.out.print("获取IP失败");
e.printStackTrace();
}
return ipaddress; } // 对象封装成消息
public byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
} // 消息解析成对象
public Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
} public static void out(String s) {
Log.v("test", s);
} public void sleepT(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
假设想要所有源代码的。能够 email 我 cq361106306@qq.com. 可是仅仅能研究所用
PS:因为博客中毒我把全部文章都删了才解封。
。
Libgdx: android单机斗地主支持局域网wifi联网的网络模块核心代码的更多相关文章
- android中百度地图定位的实现方法(仅适用于真机+WIFI联网环境)
注意:此代码的环境是:真机(系统版本为Android4.2.2)+WIFI联网(才能实现最后的运行结果):使用虚拟机调试会出现各种问题. 第一步:下载SDK和申请Key 到百度的网站http://de ...
- Android基于UDP的局域网聊天通信
代码地址如下:http://www.demodashi.com/demo/12057.html 记得把这几点描述好咯:代码实现过程 + 项目文件结构截图 + 演示效果 1. 开发环境 1.1 开发工具 ...
- 开发android App干坏事(二)-wifi控制
本来今天打算换个话题的,鉴于昨天android篇反响还不错,最近也是在做这方面的东西,今天聊聊一个新的android的发现-wifi的控制(好吧,其实也不能说是坏事,只是觉得wifi安全还是要引起警示 ...
- VS2013 MVC Web项目使用内置的IISExpress支持局域网内部机器(手机、PC)访问、调试
VS2013内置了IISExpress.做asp.net MVC的web项目开发时,Ctrl+F5和F5启动项目运行(后者是调试模式)的同时都会打开IISExpress,事实上本机对该web项目走的就 ...
- 【转并修改】VS2013 MVC Web项目使用内置的IISExpress支持局域网内部机器(手机、PC)访问、调试
转:http://www.cnblogs.com/ShaYeBlog/p/4072074.html VS2013内置了IISExpress.做asp.net MVC的web项目开发时,Ctrl+F5和 ...
- 小程序支持连Wi-Fi,代码包到4M
小程序又开发新能力了:1 更多硬件连接功能等着你.在商场等场所,用户以往要用微信连Wi-Fi,要扫二维码并关注公众号,点击菜单里的“连Wi-Fi”才能使用上网络.连个Wi-Fi何必让用户经过两道坎? ...
- JAVA面向对象编程课程设计——网络版单机斗地主
一.团队介绍 成员姓名 任务分配 成员课程设计博客链接 兰泽祥(组长) 数据库,斗地主规则的实现,人机自动出牌的算法,实体类的设计 JAVA面向对象编程课程设计--web版斗地主 吴修恩 JSP界面的 ...
- 【Android自定义控件】支持多层嵌套RadioButton的RadioGroup
前言 非常喜欢用RadioButton+RadioGroup做Tabs,能自动处理选中等效果,但是自带的RadioGroup不支持嵌套RadioButton(从源码可看出仅仅是判断子控件是不是Radi ...
- Android应用如何支持屏幕多尺寸多分辨率问题
作为Android应用程序开发者都知道android是一个“碎片化”的世界.多种系统版本.多种尺寸.多种分辨率.多种机型,还有不同的厂商定制的不同ROM,你开发的应用会在不可预期的手机上报错.这给开发 ...
随机推荐
- 机器学习——Day 2 简单线性回归
写在开头 由于某些原因开始了机器学习,为了更好的理解和深入的思考(记录)所以开始写博客. 学习教程来源于github的Avik-Jain的100-Days-Of-MLCode 英文版:https:// ...
- word文档去掉复制过来的背景颜色
选择清除格式
- Laravel5.1学习笔记8 Blade模板
简介 模板继承 定义一个页面布局模板 扩展一个页面布局模板 展示数据 控制语法的结构 Service Injection 扩展 Blade 简介 Blade 是 Laravel 提供的一个既简单又 ...
- CSS3之 transform和animation区别
CSS3 有3种和动画相关的属性:transform, transition, animation.其中 transform 描述了元素静态样式.而transition 和 animation 却都能 ...
- Android贝塞尔曲线应用-跳动的水滴
主要通过6个控制点实现. val startPoint = PointF() val endPoint = PointF() val control1 = PointF() val control2 ...
- Centos6.6 安装Memcached
一.环境介绍 1)Centos6.4 2) memcached-1.4.24 二.部署安装 计划具体部署步骤: 步骤1:安装 步骤2:配置 步骤3:运行 步骤4:检查 现在开始: 1)安装 $ yum ...
- Assembly之instruction之MOV
MOV[.W] Move source to destinationMOV.B Move source to destination Syntax MOV src,dst or M ...
- dubbo之泛化实现
实现泛化调用 泛化接口调用方式主要用于客户端没有 API 接口及模型类元的情况,参数及返回值中的所有 POJO 均用 Map 表示,通常用于框架集成,比如:实现一个通用的服务测试框架,可通过 Gene ...
- dubbo之集群容错
在集群调用失败时,Dubbo 提供了多种容错方案,缺省为 failover 重试. 集群容错模式 1. Failover Cluster 失败自动切换,当出现失败,重试其它服务器 .通常用于读操作,但 ...
- 设计包含min()函数的栈
题目:定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素.要求函数min.push以及pop的时间复杂度都是O(1). 分析:这是去年google的一道面试题. 我看到这道题目时,第一反应 ...