包裹名 | 类名 |
---|---|
mygame server | server |
mygame client | client |
mygame shared | Utilities |
每一个类的实现:
首先是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实现客户端与主机的连接