導航:首頁 > 編程語言 > java五子棋網路

java五子棋網路

發布時間:2025-05-22 19:05:20

java五子棋

我有82237475

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
class clientThread extends Thread
{
chessClient chessclient;
clientThread(chessClient chessclient)
{
this.chessclient=chessclient;
}
public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/userlist "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
int userNumber=0;
chessclient.userpad.userList.removeAll();
chessclient.inputpad.userChoice.removeAll();
chessclient.inputpad.userChoice.addItem("所有人");
while(userToken.hasMoreTokens())
{
String user=(String)userToken.nextToken(" ");
if(userNumber>0 && !user.startsWith("[inchess]"))
{
chessclient.userpad.userList.add(user);
chessclient.inputpad.userChoice.addItem(user);
}
userNumber++;
}
chessclient.inputpad.userChoice.select("所有人");
}
else if(recMessage.startsWith("/yourname "))
{
chessclient.chessClientName=recMessage.substring(10);
chessclient.setTitle("Java五子棋客戶端 "+"用戶名:"+chessclient.chessClientName);
}
else if(recMessage.equals("/reject"))
{
try
{
chessclient.chesspad.statusText.setText("不能加入游戲");
chessclient.controlpad.cancelGameButton.setEnabled(false);
chessclient.controlpad.joinGameButton.setEnabled(true);
chessclient.controlpad.creatGameButton.setEnabled(true);
}
catch(Exception ef)
{
chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close無法關閉");
}
chessclient.controlpad.joinGameButton.setEnabled(true);
}
else if(recMessage.startsWith("/peer "))
{
chessclient.chesspad.chessPeerName=recMessage.substring(6);
if(chessclient.isServer)
{
chessclient.chesspad.chessColor=1;
chessclient.chesspad.isMouseEnabled=true;
chessclient.chesspad.statusText.setText("請黑棋下子");
}
else if(chessclient.isClient)
{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戲,等待對方下子...");
}
}
else if(recMessage.equals("/youwin"))
{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);
chessclient.chesspad.statusText.setText("對方退出,請點放棄游戲退出連接");
chessclient.chesspad.isMouseEnabled=false;
}
else if(recMessage.equals("/OK"))
{
chessclient.chesspad.statusText.setText("創建游戲成功,等待別人加入...");
}
else if(recMessage.equals("/error"))
{
chessclient.chatpad.chatLineArea.append("傳輸錯誤:請退出程序,重新加入 \n");
}
else
{
chessclient.chatpad.chatLineArea.append(recMessage+"\n");
chessclient.chatpad.chatLineArea.setCaretPosition(
chessclient.chatpad.chatLineArea.getText().length());
}
}
public void run()
{
String message="";
try
{
while(true)
{
message=chessclient.in.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}
}

public class chessClient extends Frame implements ActionListener,KeyListener
{
userPad userpad=new userPad();
chatPad chatpad=new chatPad();
controlPad controlpad=new controlPad();
chessPad chesspad=new chessPad();
inputPad inputpad=new inputPad();
Socket chatSocket;
DataInputStream in;
DataOutputStream out;
String chessClientName=null;
String host=null;
int port=4331;
boolean isOnChat=false; //在聊天?
boolean isOnChess=false; //在下棋?
boolean isGameConnected=false; //下棋的客戶端連接?
boolean isServer=false; //如果是下棋的主機
boolean isClient=false; //如果是下棋的客戶端
Panel southPanel=new Panel();
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel westPanel=new Panel();
Panel eastPanel=new Panel();
chessClient()
{
super("Java五子棋客戶端");
setLayout(new BorderLayout());
host=controlpad.inputIP.getText();
westPanel.setLayout(new BorderLayout());
westPanel.add(userpad,BorderLayout.NORTH);
westPanel.add(chatpad,BorderLayout.CENTER);
westPanel.setBackground(Color.pink);
inputpad.inputWords.addKeyListener(this);
chesspad.host=controlpad.inputIP.getText();
centerPanel.add(chesspad,BorderLayout.CENTER);
centerPanel.add(inputpad,BorderLayout.SOUTH);
centerPanel.setBackground(Color.pink);
controlpad.connectButton.addActionListener(this);
controlpad.creatGameButton.addActionListener(this);
controlpad.joinGameButton.addActionListener(this);
controlpad.cancelGameButton.addActionListener(this);
controlpad.exitGameButton.addActionListener(this);
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(false);
southPanel.add(controlpad,BorderLayout.CENTER);
southPanel.setBackground(Color.pink);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);
}
public void windowActivated(WindowEvent ea)
{
}
});
add(westPanel,BorderLayout.WEST);
add(centerPanel,BorderLayout.CENTER);
add(southPanel,BorderLayout.SOUTH);
pack();
setSize(670,548);
setVisible(true);
setResizable(false);
validate();
}

public boolean connectServer(String serverIP,int serverPort) throws Exception
{
try
{
chatSocket=new Socket(serverIP,serverPort);
in=new DataInputStream(chatSocket.getInputStream());
out=new DataOutputStream(chatSocket.getOutputStream());
clientThread clientthread=new clientThread(this);
clientthread.start();
isOnChat=true;
return true;
}
catch(IOException ex)
{
chatpad.chatLineArea.setText("chessClient:connectServer:無法連接,建議重新啟動程序 \n");
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==controlpad.connectButton)
{
host=chesspad.host=controlpad.inputIP.getText();
try
{
if(connectServer(host,port))
{
chatpad.chatLineArea.setText("");
controlpad.connectButton.setEnabled(false);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
chesspad.statusText.setText("連接成功,請創建游戲或加入游戲");
}
}
catch(Exception ei)
{
chatpad.chatLineArea.setText("controlpad.connectButton:無法連接,建議重新啟動程序 \n");
}
}
if(e.getSource()==controlpad.exitGameButton)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);
}
if(e.getSource()==controlpad.joinGameButton)
{
String selectedUser=userpad.userList.getSelectedItem();
if(selectedUser==null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName))
{
chesspad.statusText.setText("必須先選定一個有效用戶");
}
else
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
else
{
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
catch(Exception ee)
{
isGameConnected=false;
isOnChess=false;
isClient=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chatpad.chatLineArea.setText("chesspad.connectServer無法連接 \n"+ee);
}
}
}
if(e.getSource()==controlpad.creatGameButton)
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
else
{
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
catch(Exception ec)
{
isGameConnected=false;
isOnChess=false;
isServer=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
ec.printStackTrace();
chatpad.chatLineArea.setText("chesspad.connectServer無法連接 \n"+ec);
}
}
if(e.getSource()==controlpad.cancelGameButton)
{
if(isOnChess)
{
chesspad.chessthread.sendMessage("/giveup "+chessClientName);
chesspad.chessVictory(-1*chesspad.chessColor);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("請建立游戲或者加入游戲");
}
if(!isOnChess)
{
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("請建立游戲或者加入游戲");
}
isClient=isServer=false;
}
}

public void keyPressed(KeyEvent e)
{
TextField inputWords=(TextField)e.getSource();
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
if(inputpad.userChoice.getSelectedItem().equals("所有人"))
{
try
{
out.writeUTF(inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed無法連接,建議重新連接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
else
{
try
{
out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed無法連接,建議重新連接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}

public static void main(String args[])
{
chessClient chessClient=new chessClient();
}
}
/******************************************************************************************
下面是:chessInteface.java
******************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class userPad extends Panel
{
List userList=new List(10);
userPad()
{
setLayout(new BorderLayout());
for(int i=0;i<50;i++)
{
userList.add(i+"."+"沒有用戶");
}
add(userList,BorderLayout.CENTER);
}
}
class chatPad extends Panel
{
TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);
chatPad()
{
setLayout(new BorderLayout());
add(chatLineArea,BorderLayout.CENTER);
}
}

class controlPad extends Panel
{
Label IPlabel=new Label("IP",Label.LEFT);
TextField inputIP=new TextField("localhost",10);
Button connectButton=new Button("連接主機");
Button creatGameButton=new Button("建立游戲");
Button joinGameButton=new Button("加入游戲");
Button cancelGameButton=new Button("放棄游戲");
Button exitGameButton=new Button("關閉程序");
controlPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setBackground(Color.pink);
add(IPlabel);
add(inputIP);
add(connectButton);
add(creatGameButton);
add(joinGameButton);
add(cancelGameButton);
add(exitGameButton);
}
}
class inputPad extends Panel
{
TextField inputWords=new TextField("",40);
Choice userChoice=new Choice();
inputPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
for(int i=0;i<50;i++)
{
userChoice.addItem(i+"."+"沒有用戶");
}
userChoice.setSize(60,24);
add(userChoice);
add(inputWords);
}
}
/**********************************************************************************************
下面是:chessPad.java
**********************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
class chessThread extends Thread
{
chessPad chesspad;
chessThread(chessPad chesspad)
{
this.chesspad=chesspad;
}
public void sendMessage(String sndMessage)
{
try
{
chesspad.outData.writeUTF(sndMessage);
}
catch(Exception ea)
{
System.out.println("chessThread.sendMessage:"+ea);
}
}
public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/chess "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
String chessToken;
String[] chessOpt={"-1","-1","0"};
int chessOptNum=0;
while(userToken.hasMoreTokens())
{
chessToken=(String)userToken.nextToken(" ");
if(chessOptNum>=1 && chessOptNum<=3)
{
chessOpt[chessOptNum-1]=chessToken;
}
chessOptNum++;
}
chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2]));
}
else if(recMessage.startsWith("/yourname "))
{
chesspad.chessSelfName=recMessage.substring(10);
}
else if(recMessage.equals("/error"))
{
chesspad.statusText.setText("錯誤:沒有這個用戶,請退出程序,重新加入");
}
else
{
//System.out.println(recMessage);
}
}
public void run()
{
String message="";
try
{
while(true)
{
message=chesspad.inData.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}
}

class chessPad extends Panel implements MouseListener,ActionListener
{
int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;
int chessBlack_x[]=new int[200];
int chessBlack_y[]=new int[200];
int chessWhite_x[]=new int[200];
int chessWhite_y[]=new int[200];
int chessBlackCount=0,chessWhiteCount=0;
int chessBlackWin=0,chessWhiteWin=0;
boolean isMouseEnabled=false,isWin=false,isInGame=false;
TextField statusText=new TextField("請先連接伺服器");
Socket chessSocket;
DataInputStream inData;
DataOutputStream outData;
String chessSelfName=null;
String chessPeerName=null;
String host=null;
int port=4331;
chessThread chessthread=new chessThread(this);
chessPad()
{
setSize(440,440);
setLayout(null);
setBackground(Color.pink);
addMouseListener(this);
add(statusText);
statusText.setBounds(40,5,360,24);
statusText.setEditable(false);
}
public boolean connectServer(String ServerIP,int ServerPort) throws Exception
{
try
{
chessSocket=new Socket(ServerIP,ServerPort);
inData=new DataInputStream(chessSocket.getInputStream());
outData=new DataOutputStream(chessSocket.getOutputStream());
chessthread.start();
return true;
}
catch(IOException ex)
{
statusText.setText("chessPad:connectServer:無法連接 \n");
}
return false;
}
public void chessVictory(int chessColorWin)
{
this.removeAll();
for(int i=0;i<=chessBlackCount;i++)
{
chessBlack_x[i]=0;
chessBlack_y[i]=0;
}
for(int i=0;i<=chessWhiteCount;i++)
{
chessWhite_x[i]=0;
chessWhite_y[i]=0;
}
chessBlackCount=0;
chessWhiteCount=0;
add(statusText);
statusText.setBounds(40,5,360,24);
if(chessColorWin==1)
{ chessBlackWin++;
statusText.setText("黑棋勝,黑:白為"+chessBlackWin+":"+chessWhiteWin+",重新開局,等待白棋下子...");
}
else if(chessColorWin==-1)
{
chessWhiteWin++;
statusText.setText("白棋勝,黑:白為"+chessBlackWin+":"+chessWhiteWin+",重新開局,等待黑棋下子...");
}
}

public void getLocation(int a,int b,int color)
{
if(color==1)
{
chessBlack_x[chessBlackCount]=a*20;
chessBlack_y[chessBlackCount]=b*20;
chessBlackCount++;
}
else if(color==-1)
{
chessWhite_x[chessWhiteCount]=a*20;
chessWhite_y[chessWhiteCount]=b*20;
chessWhiteCount++;
}
}
public boolean checkWin(int a,int b,int checkColor)
{
int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;
if(checkColor==1)
{
chessLink=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) && ((b*20)==chessBlack_y[chessCompare]))
{
chessLink=chessLink+1;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) && (b*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step<=4;step++)
{
for(chessCompare=0;chessCompare<=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) && ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;

㈡ java課程設計,做了網路五子棋,老師要我加復盤的功能,怎麼實現思路

這個很簡單。五子棋棋盤是一個二維數組,然後2數組裡面有每個位置上只能有3個值,0,1,2,0表示沒有棋子,1表示白棋,2表示黑棋。然後你用一個類把二維數組封裝起來,然後保存每一步時候的狀態就OK了。

㈢ 求一個簡單的JAVA五子棋代碼!! 網上復制的別來了!

我有一個,剛剛做的。可以實現人機對戰,人人對戰,悔棋,禁手等操作。機器方主要採用的是a-b剪枝演算法。功能很強大,代碼很多。

㈣ 急!!! Java五子棋源代碼注釋

package org.liky.game.frame;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class FiveChessFrame extends JFrame implements MouseListener, Runnable {

// 取得屏幕的寬度
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
// 取得屏幕的高度
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
// 背景圖片
BufferedImage bgImage = null;
// 保存棋子的坐標
int x = 0;
int y = 0;
// 保存之前下過的全部棋子的坐標
// 其中數據內容 0: 表示這個點並沒有棋子, 1: 表示這個點是黑子, 2:表示這個點是白子
int[][] allChess = new int[19][19];
// 標識當前應該黑棋還是白棋下下一步
boolean isBlack = true;
// 標識當前游戲是否可以繼續
boolean canPlay = true;
// 保存顯示的提示信息
String message = "黑方先行";
// 保存最多擁有多少時間(秒)
int maxTime = 0;
// 做倒計時的線程類
Thread t = new Thread(this);
// 保存黑方與白方的剩餘時間
int blackTime = 0;
int whiteTime = 0;
// 保存雙方剩餘時間的顯示信息
String blackMessage = "無限制";
String whiteMessage = "無限制";

public FiveChessFrame() {
// 設置標題
this.setTitle("五子棋");
// 設置窗體大小
this.setSize(500, 500);
// 設置窗體出現位置
this.setLocation((width - 500) / 2, (height - 500) / 2);
// 將窗體設置為大小不可改變
this.setResizable(false);
// 將窗體的關閉方式設置為默認關閉後程序結束
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 為窗體加入監聽器
this.addMouseListener(this);
// 將窗體顯示出來
this.setVisible(true);

t.start();
t.suspend();

// 刷新屏幕,防止開始游戲時出現無法顯示的情況.
this.repaint();
String imagePath = "" ;
try {
imagePath = System.getProperty("user.dir")+"/bin/image/background.jpg" ;
bgImage = ImageIO.read(new File(imagePath.replaceAll("\\\\", "/")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void paint(Graphics g) {
// 雙緩沖技術防止屏幕閃爍
BufferedImage bi = new BufferedImage(500, 500,
BufferedImage.TYPE_INT_RGB);
Graphics g2 = bi.createGraphics();
g2.setColor(Color.BLACK);
// 繪制背景
g2.drawImage(bgImage, 1, 20, this);
// 輸出標題信息
g2.setFont(new Font("黑體", Font.BOLD, 20));
g2.drawString("游戲信息:" + message, 130, 60);
// 輸出時間信息
g2.setFont(new Font("宋體", 0, 14));
g2.drawString("黑方時間:" + blackMessage, 30, 470);
g2.drawString("白方時間:" + whiteMessage, 260, 470);

// 繪制棋盤
for (int i = 0; i < 19; i++) {
g2.drawLine(10, 70 + 20 * i, 370, 70 + 20 * i);
g2.drawLine(10 + 20 * i, 70, 10 + 20 * i, 430);
}

// 標注點位
g2.fillOval(68, 128, 4, 4);
g2.fillOval(308, 128, 4, 4);
g2.fillOval(308, 368, 4, 4);
g2.fillOval(68, 368, 4, 4);
g2.fillOval(308, 248, 4, 4);
g2.fillOval(188, 128, 4, 4);
g2.fillOval(68, 248, 4, 4);
g2.fillOval(188, 368, 4, 4);
g2.fillOval(188, 248, 4, 4);

/*
* //繪制棋子 x = (x - 10) / 20 * 20 + 10 ; y = (y - 70) / 20 * 20 + 70 ;
* //黑子 g.fillOval(x - 7, y - 7, 14, 14); //白子 g.setColor(Color.WHITE) ;
* g.fillOval(x - 7, y - 7, 14, 14); g.setColor(Color.BLACK) ;
* g.drawOval(x - 7, y - 7, 14, 14);
*/

// 繪制全部棋子
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
if (allChess[i][j] == 1) {
// 黑子
int tempX = i * 20 + 10;
int tempY = j * 20 + 70;
g2.fillOval(tempX - 7, tempY - 7, 14, 14);
}
if (allChess[i][j] == 2) {
// 白子
int tempX = i * 20 + 10;
int tempY = j * 20 + 70;
g2.setColor(Color.WHITE);
g2.fillOval(tempX - 7, tempY - 7, 14, 14);
g2.setColor(Color.BLACK);
g2.drawOval(tempX - 7, tempY - 7, 14, 14);
}
}
}
g.drawImage(bi, 0, 0, this);
}

public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}

public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
/*
* System.out.println("X:"+e.getX()); System.out.println("Y:"+e.getY());
*/
if (canPlay == true) {
x = e.getX();
y = e.getY();
if (x >= 10 && x <= 370 && y >= 70 && y <= 430) {
x = (x - 10) / 20;
y = (y - 70) / 20;
if (allChess[x][y] == 0) {
// 判斷當前要下的是什麼顏色的棋子
if (isBlack == true) {
allChess[x][y] = 1;
isBlack = false;
message = "輪到白方";
} else {
allChess[x][y] = 2;
isBlack = true;
message = "輪到黑方";
}
// 判斷這個棋子是否和其他的棋子連成5連,即判斷游戲是否結束
boolean winFlag = this.checkWin();
if (winFlag == true) {
JOptionPane.showMessageDialog(this, "游戲結束,"
+ (allChess[x][y] == 1 ? "黑方" : "白方") + "獲勝!");
canPlay = false;
}
} else {
JOptionPane.showMessageDialog(this, "當前位置已經有棋子,請重新落子!");
}
this.repaint();
}
}
/* System.out.println(e.getX() + " -- " + e.getY()); */
// 點擊 開始游戲 按鈕
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 70
&& e.getY() <= 100) {
int result = JOptionPane.showConfirmDialog(this, "是否重新開始游戲?");
if (result == 0) {
// 現在重新開始游戲
// 重新開始所要做的操作: 1)把棋盤清空,allChess這個數組中全部數據歸0.
// 2) 將 游戲信息: 的顯示改回到開始位置
// 3) 將下一步下棋的改為黑方
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
allChess[i][j] = 0;
}
}
// 另一種方式 allChess = new int[19][19];
message = "黑方先行";
isBlack = true;
blackTime = maxTime;
whiteTime = maxTime;
if (maxTime > 0) {
blackMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
whiteMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
t.resume();
} else {
blackMessage = "無限制";
whiteMessage = "無限制";
}
this.canPlay = true;
this.repaint();

}
}
// 點擊 游戲設置 按鈕
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 120
&& e.getY() <= 150) {
String input = JOptionPane
.showInputDialog("請輸入游戲的最大時間(單位:分鍾),如果輸入0,表示沒有時間限制:");
try {
maxTime = Integer.parseInt(input) * 60;
if (maxTime < 0) {
JOptionPane.showMessageDialog(this, "請輸入正確信息,不允許輸入負數!");
}
if (maxTime == 0) {
int result = JOptionPane.showConfirmDialog(this,
"設置完成,是否重新開始游戲?");
if (result == 0) {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
allChess[i][j] = 0;
}
}
// 另一種方式 allChess = new int[19][19];
message = "黑方先行";
isBlack = true;
blackTime = maxTime;
whiteTime = maxTime;
blackMessage = "無限制";
whiteMessage = "無限制";
this.canPlay = true;
this.repaint();
}
}
if (maxTime > 0) {
int result = JOptionPane.showConfirmDialog(this,
"設置完成,是否重新開始游戲?");
if (result == 0) {
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
allChess[i][j] = 0;
}
}
// 另一種方式 allChess = new int[19][19];
message = "黑方先行";
isBlack = true;
blackTime = maxTime;
whiteTime = maxTime;
blackMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
whiteMessage = maxTime / 3600 + ":"
+ (maxTime / 60 - maxTime / 3600 * 60) + ":"
+ (maxTime - maxTime / 60 * 60);
t.resume();
this.canPlay = true;
this.repaint();
}
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(this, "請正確輸入信息!");
}
}
// 點擊 游戲說明 按鈕
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 170
&& e.getY() <= 200) {
JOptionPane.showMessageDialog(this,
"這個一個五子棋游戲程序,黑白雙方輪流下棋,當某一方連到五子時,游戲結束。");
}
// 點擊 認輸 按鈕
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 270
&& e.getY() <= 300) {
int result = JOptionPane.showConfirmDialog(this, "是否確認認輸?");
if (result == 0) {
if (isBlack) {
JOptionPane.showMessageDialog(this, "黑方已經認輸,游戲結束!");
} else {
JOptionPane.showMessageDialog(this, "白方已經認輸,游戲結束!");
}
canPlay = false;
}
}
// 點擊 關於 按鈕
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 320
&& e.getY() <= 350) {
JOptionPane.showMessageDialog(this,
"本游戲由MLDN製作,有相關問題可以訪問www.mldn.cn");
}
// 點擊 退出 按鈕
if (e.getX() >= 400 && e.getX() <= 470 && e.getY() >= 370
&& e.getY() <= 400) {
JOptionPane.showMessageDialog(this, "游戲結束");
System.exit(0);
}
}

public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}

private boolean checkWin() {
boolean flag = false;
// 保存共有相同顏色多少棋子相連
int count = 1;
// 判斷橫向是否有5個棋子相連,特點 縱坐標 是相同, 即allChess[x][y]中y值是相同
int color = allChess[x][y];
/*
* if (color == allChess[x+1][y]) { count++; if (color ==
* allChess[x+2][y]) { count++; if (color == allChess[x+3][y]) {
* count++; } } }
*/
// 通過循環來做棋子相連的判斷
/*
* int i = 1; while (color == allChess[x + i][y + 0]) { count++; i++; }
* i = 1; while (color == allChess[x - i][y - 0]) { count++; i++; } if
* (count >= 5) { flag = true; } // 縱向的判斷 int i2 = 1 ; int count2 = 1 ;
* while (color == allChess[x + 0][y + i2]) { count2++; i2++; } i2 = 1;
* while (color == allChess[x - 0][y - i2]) { count2++; i2++; } if
* (count2 >= 5) { flag = true ; } // 斜方向的判斷(右上 + 左下) int i3 = 1 ; int
* count3 = 1 ; while (color == allChess[x + i3][y - i3]) { count3++;
* i3++; } i3 = 1; while (color == allChess[x - i3][y + i3]) { count3++;
* i3++; } if (count3 >= 5) { flag = true ; } // 斜方向的判斷(右下 + 左上) int i4 =
* 1 ; int count4 = 1 ; while (color == allChess[x + i4][y + i4]) {
* count4++; i4++; } i4 = 1; while (color == allChess[x - i4][y - i4]) {
* count4++; i4++; } if (count4 >= 5) { flag = true ; }
*/

// 判斷橫向
count = this.checkCount(1, 0, color);
if (count >= 5) {
flag = true;
} else {
// 判斷縱向
count = this.checkCount(0, 1, color);
if (count >= 5) {
flag = true;
} else {
// 判斷右上、左下
count = this.checkCount(1, -1, color);
if (count >= 5) {
flag = true;
} else {
// 判斷右下、左上
count = this.checkCount(1, 1, color);
if (count >= 5) {
flag = true;
}
}
}
}

return flag;
}

// 判斷棋子連接的數量
private int checkCount(int xChange, int yChange, int color) {
int count = 1;
int tempX = xChange;
int tempY = yChange;
while (x + xChange >= 0 && x + xChange <= 18 && y + yChange >= 0
&& y + yChange <= 18
&& color == allChess[x + xChange][y + yChange]) {
count++;
if (xChange != 0)
xChange++;
if (yChange != 0) {
if (yChange > 0)
yChange++;
else {
yChange--;
}
}
}
xChange = tempX;
yChange = tempY;
while (x - xChange >= 0 && x - xChange <= 18 && y - yChange >= 0
&& y - yChange <= 18
&& color == allChess[x - xChange][y - yChange]) {
count++;
if (xChange != 0)
xChange++;
if (yChange != 0) {
if (yChange > 0)
yChange++;
else {
yChange--;
}
}
}
return count;
}

public void run() {
// TODO Auto-generated method stub
// 判斷是否有時間限制
if (maxTime > 0) {
while (true) {
if (isBlack) {
blackTime--;
if (blackTime == 0) {
JOptionPane.showMessageDialog(this, "黑方超時,游戲結束!");
}
} else {
whiteTime--;
if (whiteTime == 0) {
JOptionPane.showMessageDialog(this, "白方超時,游戲結束!");
}
}
blackMessage = blackTime / 3600 + ":"
+ (blackTime / 60 - blackTime / 3600 * 60) + ":"
+ (blackTime - blackTime / 60 * 60);
whiteMessage = whiteTime / 3600 + ":"
+ (whiteTime / 60 - whiteTime / 3600 * 60) + ":"
+ (whiteTime - whiteTime / 60 * 60);
this.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(blackTime + " -- " + whiteTime);
}
}
}

}

㈤ java五子棋代碼帶詳細解釋

浩大的工程 你有五子棋程序 如果你水平還行的話你參照這個聊天室程序應該也比較容易寫出人人對戰的
package Chat;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;

/**
* 聊天室的客戶端程序,GUI界面。
*/
public class ChatClient extends JFrame implements ActionListener{

// 登陸聊天室的名字標簽和輸入框
JLabel nameLabel = new JLabel();
JTextField nameTextField = new JTextField(15);

// 連接和斷開連接的按鈕
JButton connectButton = new JButton();
JButton disConnectButton = new JButton();

// 聊天室內容的文本域
JTextArea chatContentTextArea = new JTextArea(9, 30);

// 發送消息的按鈕
JButton sendMsgButton = new JButton();
// 消息輸入框
JTextField msgTextField = new JTextField(20);
JLabel msglabel = new JLabel();
// 聊天室用戶列表
java.awt.List peopleList = new java.awt.List(10);

/*以下定義數據流和網路變數*/
Socket soc = null;
PrintStream ps = null;

// 客戶端偵聽伺服器消息的線程
ClentListener listener = null;

public ChatClient() {
init();
}

// 初始化圖形界面
public void init() {

this.setTitle("聊天室客戶端");

// 初始化按鈕和標簽
nameLabel.setText("姓名:");
connectButton.setText("連 接");
connectButton.addActionListener(this);
disConnectButton.setText("斷 開");
disConnectButton.addActionListener(this);
// 設置聊天內容不可編輯
chatContentTextArea.setEditable(false);
sendMsgButton.setText("發 送");
sendMsgButton.addActionListener(this);
msgTextField.setText("請輸入聊天信息");

//panel1放置輸入姓名和連接兩個按鈕
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.add(nameLabel);
panel1.add(nameTextField);
panel1.add(connectButton);
panel1.add(disConnectButton);

//用於放置聊天信息顯示和聊天人員列表
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
JScrollPane pane1 = new JScrollPane(chatContentTextArea);
pane1.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "聊天內容"));
panel2.add(pane1);
JScrollPane pane2 = new JScrollPane(peopleList);
pane2.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "用戶列表"));
panel2.add(pane2);

//用於放置發送信息區域
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.add(msglabel);
panel3.add(msgTextField);
panel3.add(sendMsgButton);

// 將組件添加到界面
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(panel1, BorderLayout.NORTH);
this.getContentPane().add(panel2, BorderLayout.CENTER);
this.getContentPane().add(panel3, BorderLayout.SOUTH);

this.pack();

try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 關閉聊天室客戶端事件
*/
protected void processWindowEvent(WindowEvent e){
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
// 如果是關閉聊天室客戶端,則斷開連接
disconnect();
dispose();
System.exit(0);
}
}

/**
* 處理按鈕事件
*/
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == connectButton){
// 如果點擊連接按鈕
if (soc == null) {
try {
// 使用埠2525實例化一個本地套接字
soc = new Socket(InetAddress.getLocalHost(), Constants.SERVER_PORT);
// 在控制台列印實例化的結果
System.out.println(soc);
//將ps指向soc的輸出流
ps = new PrintStream(soc.getOutputStream());
//定義一個字元緩沖存儲發送信息
StringBuffer info = new StringBuffer(Constants.CONNECT_IDENTIFER).append(Constants.SEPERATOR);
//其中INFO為關鍵字讓伺服器識別為連接信息
//並將name和ip用":"分開,在伺服器端將用一個
//StringTokenizer類來讀取數據
String userinfo = nameTextField.getText() + Constants.SEPERATOR
+ InetAddress.getLocalHost().getHostAddress();
ps.println(info.append(userinfo));

ps.flush();
//將客戶端線程實例化,並啟動
listener = new ClentListener(this, nameTextField.getText(), soc);
listener.start();
} catch (IOException e) {
System.out.println("Error:" + e);
disconnect();
}
}

} else if (source == disConnectButton){
// 如果點擊斷開連接按鈕
disconnect();

} else if (source == sendMsgButton) {
//如果點擊發送按鈕
if (soc != null) {
//定義並實例化一個字元緩沖存儲發送的聊天信息
StringBuffer msg = new StringBuffer(Constants.MSG_IDENTIFER).append(Constants.SEPERATOR);
//用列印流發送聊天信息
ps.println(msg.append(msgTextField.getText()));
ps.flush();
}
}
}

/**
* 斷開與伺服器的連接
*/
public void disconnect(){
if (soc != null) {
try {
// 用列印流發送QUIT信息通知伺服器斷開此次通信
ps.println(Constants.QUIT_IDENTIFER);
ps.flush();
soc.close(); //關閉套接字
listener.toStop();
soc = null;
} catch (IOException e) {
System.out.println("Error:" + e);
}
}
}

public static void main(String[] args){
ChatClient client = new ChatClient();
client.setVisible(true);
}

/**
* 客戶端線程類用來監聽伺服器傳來的信息
*/
class ClentListener extends Thread {
//存儲客戶端連接後的name信息
String name = null;
//客戶端接受伺服器數據的輸入流
BufferedReader br = null;
//實現從客戶端發送數據到伺服器的列印流
PrintStream ps = null;

//存儲客戶端的socket信息
Socket socket = null;
//存儲當前運行的ChatClient實例
ChatClient parent = null;

boolean running = true;

//構造方法
public ClentListener(ChatClient p, String n, Socket s) {

//接受參數
parent = p;
name = n;
socket = s;

try {
//實例化兩個數據流
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
ps = new PrintStream(s.getOutputStream());

} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
}

// 停止偵聽
public void toStop(){
this.running = false;
}

//線程運行方法
public void run(){
String msg = null;
while (running) {
msg = null;
try {
// 讀取從伺服器傳來的信息
msg = br.readLine();
System.out.println("receive msg: " + msg);
} catch (IOException e) {
System.out.println("Error:" + e);
parent.disconnect();
}
// 如果從伺服器傳來的信息為空則斷開此次連接
if (msg == null) {
parent.listener = null;
parent.soc = null;
parent.peopleList.removeAll();
running = false;
return;
}

//用StringTokenizer類來實現讀取分段字元
StringTokenizer st = new StringTokenizer(msg, Constants.SEPERATOR);
//讀取信息頭即關鍵字用來識別是何種信息
String keyword = st.nextToken();

if (keyword.equals(Constants.PEOPLE_IDENTIFER)) {
//如果是PEOPLE則是伺服器發來的客戶連接信息
//主要用來刷新客戶端的用戶列表
parent.peopleList.removeAll();
//遍歷st取得目前所連接的客戶
while (st.hasMoreTokens()) {
String str = st.nextToken();
parent.peopleList.add(str);
}

} else if (keyword.equals(Constants.MSG_IDENTIFER)) {
//如果關鍵字是MSG則是伺服器傳來的聊天信息,
//主要用來刷新客戶端聊天信息區將每個客戶的聊天內容顯示出來
String usr = st.nextToken();
parent.chatContentTextArea.append(usr);
parent.chatContentTextArea.append(st.nextToken("\0"));
parent.chatContentTextArea.append("\r\n");

} else if (keyword.equals(Constants.QUIT_IDENTIFER)) {
//如果關鍵字是QUIT則是伺服器關閉的信息, 切斷此次連接
System.out.println("Quit");
try {
running = false;
parent.listener = null;
parent.soc.close();
parent.soc = null;
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
parent.soc = null;
parent.peopleList.removeAll();
}

break;
}
}
//清除用戶列表
parent.peopleList.removeAll();
}
}
}

package Chat;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;

/**
* 聊天室的伺服器端程序,GUI界面
*/
public class ChatServer extends JFrame {

// 狀態欄標簽
static JLabel statusBar = new JLabel();
// 顯示客戶端的連接信息的列表
static java.awt.List connectInfoList = new java.awt.List(10);

// 保存當前處理客戶端請求的處理器線程
static Vector clientProcessors = new Vector(10);
// 當前的連接數
static int activeConnects = 0;

// 構造方法
public ChatServer() {
init();
try {
// 設置界面為系統默認外觀
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}

private void init(){
this.setTitle("聊天室伺服器");
statusBar.setText("");

// 初始化菜單
JMenu fileMenu = new JMenu();
fileMenu.setText("文件");
JMenuItem exitMenuItem = new JMenuItem();
exitMenuItem.setText("退出");
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exitActionPerformed(e);
}
});
fileMenu.add(exitMenuItem);

JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);

// 將組件進行布局
JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
JScrollPane pane = new JScrollPane(connectInfoList);
pane.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(
Color.white, new Color(134, 134, 134)), "客戶端連接信息"));
jPanel1.add(new JScrollPane(pane), BorderLayout.CENTER);

this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(statusBar, BorderLayout.SOUTH);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);

this.pack();
}

/**
* 退出菜單項事件
* @param e
*/
public void exitActionPerformed(ActionEvent e){
// 向客戶端發送斷開連接信息
sendMsgToClients(new StringBuffer(Constants.QUIT_IDENTIFER));
// 關閉所有的連接
closeAll();
System.exit(0);
}

/**
* 處理窗口關閉事件
*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
exitActionPerformed(null);
}
}

/**
* 刷新聊天室,不斷刷新clientProcessors,製造最新的用戶列表
*/
public static void notifyRoomPeople(){
StringBuffer people = new StringBuffer(Constants.PEOPLE_IDENTIFER);
for (int i = 0; i < clientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
people.append(Constants.SEPERATOR).append(c.clientName);
}
// 用sendClients方法向客戶端發送用戶列表的信息
sendMsgToClients(people);
}

/**
* 向所有客戶端群發消息
* @param msg
*/
public static synchronized void sendMsgToClients(StringBuffer msg) {
for (int i = 0; i < clientProcessors.size(); i++) {
ClientProcessor c = (ClientProcessor) clientProcessors.elementAt(i);
System.out.println("send msg: " + msg);
c.send(msg);
}
}

/**
* 關閉所有連接
*/
public static void closeAll(){
while (clientProcessors.size() > 0) {
ClientProcessor c = (ClientProcessor) clientProcessors.firstElement();
try {
// 關閉socket連接和處理線程
c.socket.close();
c.toStop();
} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
clientProcessors.removeElement(c);
}
}
}

/**
* 判斷客戶端是否合法。
* 不允許同一客戶端重復登陸,所謂同一客戶端是指IP和名字都相同。
* @param newclient
* @return
*/
public static boolean checkClient(ClientProcessor newclient){
if (clientProcessors.contains(newclient)){
return false;
} else {
return true;
}
}

/**
* 斷開某個連接,並且從連接列表中刪除
* @param client
*/
public static void disconnect(ClientProcessor client){
disconnect(client, true);
}

/**
* 斷開某個連接,根據要求決定是否從連接列表中刪除
* @param client
* @param toRemoveFromList
*/
public static synchronized void disconnect(ClientProcessor client, boolean toRemoveFromList){
try {
//在伺服器端程序的list框中顯示斷開信息
connectInfoList.add(client.clientIP + "斷開連接");

ChatServer.activeConnects--; //將連接數減1
String constr = "目前有" + ChatServer.activeConnects + "客戶相連";
statusBar.setText(constr);
//向客戶發送斷開連接信息
client.send(new StringBuffer(Constants.QUIT_IDENTIFER));
client.socket.close();

} catch (IOException e) {
System.out.println("Error:" + e);
} finally {
//從clients數組中刪除此客戶的相關socket等信息, 並停止線程。
if (toRemoveFromList) {
clientProcessors.removeElement(client);
client.toStop();
}
}
}

public static void main(String[] args) {

ChatServer chatServer1 = new ChatServer();
chatServer1.setVisible(true);
System.out.println("Server starting ...");

ServerSocket server = null;
try {
// 伺服器端開始偵聽
server = new ServerSocket(Constants.SERVER_PORT);
} catch (IOException e) {
System.out.println("Error:" + e);
System.exit(1);
}
while (true) {
// 如果當前客戶端數小於MAX_CLIENT個時接受連接請求
if (clientProcessors.size() < Constants.MAX_CLIENT) {
Socket socket = null;
try {
// 收到客戶端的請求
socket = server.accept();
if (socket != null) {
System.out.println(socket + "連接");
}
} catch (IOException e) {
System.out.println("Error:" + e);
}

// 定義並實例化一個ClientProcessor線程類,用於處理客戶端的消息
ClientProcessor c = new ClientProcessor(socket);
if (checkClient(c)) {
// 添加到列表
clientProcessors.addElement(c);
// 如果客戶端合法,則繼續
int connum = ++ChatServer.activeConnects;
// 在狀態欄里顯示連接數
String constr = "目前有" + connum + "客戶相連";
ChatServer.statusBar.setText(constr);
// 將客戶socket信息寫入list框
ChatServer.connectInfoList.add(c.clientIP + "連接");
c.start();
// 通知所有客戶端用戶列表發生變化
notifyRoomPeople();
} else {
//如果客戶端不合法
c.ps.println("不允許重復登陸");
disconnect(c, false);
}

} else {
//如果客戶端超過了MAX_CLIENT個,則等待一段時間再嘗試接受請求
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
}
}

/**
* 處理客戶端發送的請求的線程
*/
class ClientProcessor extends Thread {
//存儲一個連接客戶端的socket信息
Socket socket;
//存儲客戶端的連接姓名
String clientName;

//存儲客戶端的ip信息
String clientIP;

//用來實現接受從客戶端發來的數據流
BufferedReader br;
//用來實現向客戶端發送信息的列印流
PrintStream ps;

boolean running = true;

/**
* 構造方法
* @param s
*/
public ClientProcessor(Socket s) {
socket = s;
try {
// 初始化輸入輸出流
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
// 讀取收到的信息,第一條信息是客戶端的名字、IP信息
String clientInfo = br.readLine();

// 讀取信息,根據消息分隔符解析消息
StringTokenizer stinfo = new StringTokenizer(clientInfo, Constants.SEPERATOR);
String head = stinfo.nextToken();
if (head.equals(Constants.CONNECT_IDENTIFER)){
if (stinfo.hasMoreTokens()){
//關鍵字後的第二段數據是客戶名信息
clientName = stinfo.nextToken();
}
if (stinfo.hasMoreTokens()){
//關鍵字後的第三段數據是客戶ip信息
clientIP = stinfo.nextToken();
}
System.out.println(head); //在控制台列印頭信息
}
} catch (IOException e) {
System.out.println("Error:" + e);
}
}

/**
* 向客戶端發送消息
* @param msg
*/
public void send(StringBuffer msg) {
ps.println(msg);
ps.flush();
}

//線程運行方法
public void run() {

while (running) {
String line = null;
try {
//讀取客戶端發來的數據流
line = br.readLine();

} catch (IOException e) {
System.out.println("Error" + e);
ChatServer.disconnect(this);
ChatServer.notifyRoomPeople();
return;
}
//客戶已離開
if (line == null){
ChatServer.disconnect(this);
ChatServer.notifyRoomPeople();
return;
}

StringTokenizer st = new StringTokenizer(line, Constants.SEPERATOR);
String keyword = st.nextToken();

// 如果關鍵字是MSG則是客戶端發來的聊天信息
if (keyword.equals(Constants.MSG_IDENTIFER)){
StringBuffer msg = new StringBuffer(Constants.MSG_IDENTIFER).append(Constants.SEPERATOR);
msg.append(clientName);
msg.append(st.nextToken("\0"));
// 再將某個客戶發來的聊天信息發送到每個連接客戶的聊天欄中
ChatServer.sendMsgToClients(msg);

} else if (keyword.equals(Constants.QUIT_IDENTIFER)) {
// 如果關鍵字是QUIT則是客戶端發來斷開連接的信息

// 伺服器斷開與這個客戶的連接
ChatServer.disconnect(this);
// 繼續監聽聊天室並刷新其他客戶的聊天人名list
ChatServer.notifyRoomPeople();
running = false;
}
}
}

public void toStop(){
running = false;
}

// 覆蓋Object類的equals方法
public boolean equals(Object obj){
if (obj instanceof ClientProcessor){
ClientProcessor obj1 = (ClientProcessor)obj;
if (obj1.clientIP.equals(this.clientIP) &&
(obj1.clientName.equals(this.clientName))){
return true;
}
}
return false;
}

// 覆蓋Object類的hashCode方法
public int hashCode(){
return (this.clientIP + Constants.SEPERATOR + this.clientName).hashCode();
}
}

package Chat;

/**
* 定義聊天室程序中用到的常量
*/
public class Constants {

// 伺服器的埠號
public static final int SERVER_PORT = 2525;
public static final int MAX_CLIENT = 10;

// 消息標識符與消息體之間的分隔符
public static final String SEPERATOR = ":";

// 消息信息的標識符
public static final String MSG_IDENTIFER = "MSG";
// 用戶列表信息的標識符
public static final String PEOPLE_IDENTIFER = "PEOPLE";
// 連接伺服器信息的標識符
public static final String CONNECT_IDENTIFER = "INFO";
// 退出信息標識符
public static final String QUIT_IDENTIFER = "QUIT";

}

閱讀全文

與java五子棋網路相關的資料

熱點內容
最小語法單位編譯原理 瀏覽:570
如何批量看文件夾是否為空 瀏覽:986
java與jsp的區別 瀏覽:409
單片機紅外接收 瀏覽:122
oppo4g應用加密在哪裡設置 瀏覽:770
p6程序員面試官 瀏覽:762
滿堂腳手架演算法 瀏覽:876
國內流行php框架 瀏覽:25
計算機軟體編程專業 瀏覽:605
stm8與單片機 瀏覽:353
手機app上怎麼買語音套餐 瀏覽:723
油話APP充值余額怎麼用 瀏覽:93
pdf列印機找不到列印機 瀏覽:440
程序員體力活就業 瀏覽:462
怎麼自己做一個app 瀏覽:695
非暴力溝通pdf 瀏覽:114
戴爾伺服器raid5如何刪除 瀏覽:515
app展示模板怎麼用 瀏覽:475
java中的變數是什麼 瀏覽:716
伺服器閑置可以做什麼 瀏覽:798