一个简单的java socket编程例子

关于scoekt的一些介绍,请参加度娘上的内容,链接为:http://baike.baidu.com/view/13870.htm


下面是自己写的一个socket的小例子,当前功能只是初步调试了下。


服务端代码如下:

import java.awt.AWTException;
import java.awt.Robot;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static Robot mRobot;
	private static ServerSocket serverSocket;
	private static DataInputStream in;

	class ServerThread implements Runnable {
		private ServerSocket mServerSocket;

		public ServerThread(ServerSocket serverSocket) {
			mServerSocket = serverSocket;
		}

		@Override
		public void run() {
			while (true) {
				try {
					System.out.println("awaiting....");
					Socket socket = mServerSocket.accept();
					in = new DataInputStream(new BufferedInputStream(
							socket.getInputStream()));
					String cmd = "";
					while (!(cmd = in.readUTF()).equals("BYE")) {
						System.out.println("cmd is "+cmd);
						int xPoint = Integer.parseInt(cmd.split(";")[0]);
						int yPoint = Integer.parseInt(cmd.split(";")[1]);
						mRobot.mouseMove(xPoint, yPoint);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private void start() {
		new Thread(new ServerThread(serverSocket)).start();
	}

	private void init() {
		try {
			serverSocket = new ServerSocket(10101);
			mRobot = new Robot();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (AWTException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Server mServer = new Server();
		mServer.init();
		mServer.start();
	}

}

客户端代码如下:

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	private Socket socket;
	private DataOutputStream out;

	private void init() {
		try {
			socket = new Socket("localhost", 10101);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void send() {
		try {
			out = new DataOutputStream(new BufferedOutputStream(
					socket.getOutputStream()));
			for (int i = 100; i <= 200; i++) {
				out.writeUTF(i + ";" + i);
				out.flush();
			}
			out.writeUTF("BYE");
			out.flush();
		} catch (Exception e) {

		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Client client = new Client();
		client.init();
		client.send();
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值