首先是写一个Server类,这个类用来监听10000端口,并从这个端口接收消息然后输出,当收到“bye”时退出。
packagecom.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); //服务器在10000端口监听
Socket client =server.accept(); //得到连接,程序进入堵塞状态
BufferedReader in = new BufferedReader(new InputStreamReader(client.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;
}
}
client.close();
}
}
然后是一个Client类,这个类连接上面启动的Server类,然后接收任何用户输入,当遇到回车时发送字符串到Server上,当输入“bye”是退出。
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 voidmain(String[] args) throws Exception {
Socket client = newSocket("localhost", 10000);
BufferedReader in =new BufferedReader(new InputStreamReader(client.getInputStream())); //接收服务器端信息
PrintWriter out = newPrintWriter(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());
}
client.close();
}
}
最后,首先运行MyServer类,然后MyClient类,然后在MyClient的控制台输入任意字符,可以看到当输入bye是server和client都会退出。