在上次发表类似文章的基础上做了一点手脚,这次可以直接运行两个控制台,不用再去用telnet IP端口了,这个可以直接在eclipse分别执行服务器端类和客户端类,然后在客户端和服务端上进行交互。更为方便。我的代码实现如下:
首先我的文件结构是
在ServerDemo.java中编写以下代码:
package ;import java.io.IOException;import java.io.PrintWriter;import .ServerSocket;import .Socket;import java.util.Scanner;public class ServerDemo {//服务器public static void testServer(){//创建一个服务器System.out.println("等待客户端连接。。。");PrintWriter pwtoclien = null;Scanner keybordscanner = null;Scanner inScanner = null;ServerSocket ss = null;try {ss = new ServerSocket(6666);//创建一个接收连接客户端的对象Socket socket = ss.accept();System.out.println(socket.getInetAddress()+"已成功连接到此台服务器上。");//字符输出流pwtoclien = new PrintWriter(socket.getOutputStream());pwtoclien.println("已成功连接到远程服务器!"+"\t"+"请您先发言。");pwtoclien.flush();keybordscanner = new Scanner(System.in);inScanner = new Scanner(socket.getInputStream());//阻塞等待客户端发送消息过来while(inScanner.hasNextLine()){String indata = inScanner.nextLine();System.out.println("客户端:"+indata);System.out.print("我(服务端):");String keyborddata = keybordscanner.nextLine();System.out.println("我(服务端):"+keyborddata);pwtoclien.println(keyborddata);pwtoclien.flush();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {pwtoclien.close();keybordscanner.close();inScanner.close();try {ss.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void main(String[] args) {testServer();}}
在ClientDemo.java中编写以下代码:
package ;import java.io.IOException;import java.io.PrintWriter;import .Socket;import .UnknownHostException;import java.util.Scanner;public class ClientDemo {public static void testClient(){System.out.println("正在向服务器请求连接。。。");Socket socket = null;Scanner keybordscanner = null;Scanner inScanner = null;PrintWriter pwtoserver = null;try {socket = new Socket("192.168.0.12", 6666);inScanner = new Scanner(socket.getInputStream()); System.out.println(inScanner.nextLine());pwtoserver = new PrintWriter(socket.getOutputStream());System.out.print("我(客户端):");//先读取键盘录入方可向服务端发送消息keybordscanner = new Scanner(System.in);while(keybordscanner.hasNextLine()){String keyborddata = keybordscanner.nextLine();//展示到己方的控制台System.out.println("我(客户端):"+keyborddata);//写到服务端的的控制台pwtoserver.println(keyborddata);pwtoserver.flush();//阻塞等待接收服务端的消息String indata = inScanner.nextLine();System.out.println("服务端:"+indata);System.out.print("我(客户端):");}} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {keybordscanner.close();pwtoserver.close();inScanner.close();try {socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void main(String[] args) {testClient();}}
效果如下:
ServerDemo的控制台的显示结果
ClientDemo的控制台的显示结果