关于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();
}
}