本文地址:http://blog.csdn.net/kongxx/article/details/7259436
现在做Java直接使用Socket的情况是越来越少,因为有很多的选择可选,比如说可以用spring,其中就可以支持很多种远程连接的操作,另外jboss的remoting也是不错的选择,还有Apache的Mina等等,但是在有些时候一些特殊情况仍然逃脱不了直接写Socket的情况,比如公司内部一些莫名其妙的游戏规则。
废话不说了,下面就看看如果自己写Socket应该怎么做吧。
首先是写一个Server类,这个类用来监听10000端口,并从这个端口接收消息然后输出,当收到“bye”时退出。
[java] view plain copy print?
- package com.googlecode.garbagecan.test.socket.sample1;
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
-
- public class MyServer {
- public static void main(String[] args) throws IOException {
- ServerSocket server = new ServerSocket(10000);
- Socket socket = server.accept();
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter out = new PrintWriter(socket.getOutputStream());
-
- while (true) {
- String msg = in.readLine();
- System.out.println(msg);
- out.println("Server received " + msg);
- out.flush();
- if (msg.equals("bye")) {
- break;
- }
- }
- socket.close();
- }
- }
然后是一个Client类,这个类连接上面启动的Server类,然后接收任何用户输入,当遇到回车时发送字符串到Server上,当输入“bye”是退出。
[java] view plain copy print?
- package com.googlecode.garbagecan.test.socket.sample1;
-
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
-
- public class MyClient {
- public static void main(String[] args) throws Exception {
- Socket socket = new Socket("localhost", 10000);
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- PrintWriter out = new PrintWriter(socket.getOutputStream());
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
-
- while (true) {
- String msg = reader.readLine();
- out.println(msg);
- out.flush();
- if (msg.equals("bye")) {
- break;
- }
- System.out.println(in.readLine());
- }
- socket.close();
- }
- }
最后,首先运行MyServer类,然后MyClient类,然后在MyClient的控制台输入任意字符,可以看到当输入bye是server和client都会退出。