【Java Tutorial-package】mygame类的实现分析

包裹名类名
mygame serverserver
mygame clientclient
mygame sharedUtilities

每一个类的实现:
首先是share,用于传递信息和放置公用——

package mygame.shared;

public class Utilities {
    // set DEBUG = false and compile to stop debug messages
    final static boolean DEBUG = true;

    public static void printMsg(String msg) {
	if (DEBUG) {
	    System.out.println(msg);
	}
    }
}

接下来是客户端

package mygame.client;//首先要声名一个包

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

import mygame.shared.Utilities;

public class Client extends Thread {
    Socket clientSocket = null;
    /*thread类与runnable等进程线程操作相关 
    socket套接字用于实现client与其他类之间的通信与数据传递
    此处声名了一个socket为clientSocket*/

    public Client(Socket s) {
	clientSocket = s;//实现赋值的方法
    }

    public void run() {
	if (clientSocket == null) {
	    return;
	}

	PrintStream out = null;//定义输出流为空

	Utilities.printMsg("creating output stream");//输出这句话

	try {
	    out = new PrintStream(clientSocket.getOutputStream());
	    /*定义输出流为getOut的套接字输出流*/
	} catch (IOException e) {
	    System.err.println("Error binding output to socket, " + e); 
	    System.exit(1);
	}//用try+catch结构输出异常并跳出

	Utilities.printMsg("writing current date");

	Date d = new Date();
	/*newdate也不一定是只能输出当年当月当日的本机时间
	可以直接使用 Date date = new Date(2016-1900,8-1,28);
	并且用systemoutp来输出,但是要注意在年份上减去1900;
	或者使用Calendar对象加以构造
	Calendar c1 = Calendar.getInstance();
    c1.set(2016,8-1,28);*/
   
	out.println(d);

	try {          
	    out.close();
	    clientSocket.close();//关闭套接字
	} catch (IOException e) {
	}
    }

    protected void finalize() {
	if (clientSocket != null) {
	    try {
		clientSocket.close();
	    } catch (IOException e) {
	    }
	    clientSocket = null;
	}
    }  //finalize个人觉得用处不大
}


最后是server部分

package mygame.server;

import java.io.*;
import java.net.*;

import mygame.client.Client;
import mygame.shared.Utilities;
//由于已经有了client与utilities两个类,需要把接口都放进来

public class Server {

    public static void main(String args[]) {
	ServerSocket serverSocket = null;//同样声名一个套接字

	Utilities.printMsg("creating server socket");
	
	try {
	    serverSocket = new ServerSocket(4444);//占用接口4444
	} catch (IOException e) {
	    System.err.println("Unable to create server socket, " + e);
	    System.exit(1);
	}

	Utilities.printMsg("accepting client connections");

	while (true) {
	    try {
		Socket clientSocket = serverSocket.accept();//接受连接请求
		new Client(clientSocket).start();
	    } catch (IOException e) {
		System.err.println("Unable to accept socket connection, " + e); 
		System.exit(1);//报错并输出
	    }
	}
    }
}

参考了另外一个博客:java实现客户端与主机的连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值