| 网站首页 | JAVA文章 | AppServers | Web开发 | 应用开发 | 资源下载 |
    想学好编程,学好外语很重要  [enadd  2006年12月25日]        
设为首页 加入收藏 联系站长
您现在的位置: 编程笔记网 >> JAVA文章 >> java socket >> 文章正文
如何用Java实现网络中国象棋室(二)        【字体:
如何用Java实现网络中国象棋室(二)
作者:-    文章来源:-    点击数:    更新时间:2006-7-24

ull;

public ChessUser(String un,int ui,Socket st){
username=un;
userID=ui;
socket=st;
System.arraycopy(username.getBytes(),0,data,0,Math.min(8,username.getBytes().length));
System.arraycopy(Convert.intToBytes(ui),0,data,8,4);
data[12]=(byte)-1;
data[13]=(byte)-1;
}
public boolean init(){
try{
sender=new TcpDataSender(socket.getOutputStream());
receiver=new TcpDataReceiver(socket.getInputStream());
receiver.addTcpDataListener(this);
return true;
}catch(IOException e){}
return false;
}
public void setState(int stat){
state=stat;
data[13]=(byte)stat;
}
public void start(){
try{
sender.sendLoginBack(userID);
receiver.start();
}catch(Exception e){}
}
public void onTcpDataArrived(TcpDataEvent evt){
ChessServer.hwnd.onUserPackageArrived(evt.getHeader(),evt.getDataLen(),evt.getData());
}
public byte[] getBytes(){
return data;
}
public void close(){
try{
if(socket!=null){
socket.close();
socket=null;
}
}catch(Exception e){}
try{
if(receiver!=null){
receiver.setRunning(false);
receiver=null;
}
}catch(Exception e){}
try{
if(sender!=null)sender=null;
}catch(Exception e){}
}
}
4、TCP数据接收器:
package sunstudio.netlib;

import java.util.*;
import java.net.*;
import java.io.*;
import sunstudio.util.*;

public class TcpDataReceiver extends Thread{

Vector listeners=new Vector();
boolean isrunning=true;
InputStream is=null;

byte[] h=new byte[12];
byte[] d=new byte[1024];
int l=0;

public TcpDataReceiver(InputStream s){
is=s;
}
public void run(){
try{
while(isrunning){
HttpInputStream.readBytes(is,12,h);
l=Convert.byteToShort(h[1],h[2]);
if(l>0)HttpInputStream.readBytes(is,l,d);
if(l>0)notifyListeners(h,l,d);
else if(l==0)notifyListeners(h,0,null);
else throw new IOException();
}
}catch(IOException e){
System.out.println("读取流数据异常!");
//异常处理,关闭socket
}
}
public void addTcpDataListener(TcpDataListener hrl){
listeners.addElement(hrl);
}
synchronized void notifyListeners(byte[] hh,int ll,byte[] dd){
TcpDataEvent evt=new TcpDataEvent(hh,ll,dd);
for(Enumeration enumeration=listeners.elements();enumeration.hasMoreElements();((TcpDataListener)enumeration.nextElement()).onTcpDataArrived(evt));

上一页  [1] [2] [3] [4] [5] 下一页  

文章录入:enadd    责任编辑:enadd 
  • 上一篇文章:

  • 下一篇文章:
  • 发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
    最新热点 最新推荐 相关文章
  • HTTP 1.1状态代码及其含义

  • java开发的邮件发送程序

  • 从socket中读取数据时使用超…

  • 对等计算实践:基于 IP 多播…

  • 穿透Socks5 代理的UDP编程

  • 使用Java控制UDP协议

  • 一个Socket服务器样板程序

  • Java Socket编程

  • Java Socket编程之五

  • Java Socket编程之四

  •   网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)
    | 设为首页 | 加入收藏 | 联系站长 | 友情链接 | 版权申明 | 管理登录 |