Server端:

package com.hqh.hello.test;

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 Server {
public static final int SERVER_PORT = 8888;

public void startServer() {
try {
// 创建绑定到特定端口的服务器套接字。
ServerSocket ss = new ServerSocket(SERVER_PORT);
// 时刻监听客户端的连接
while (true) {
System.out.println("等待客户端发起连接。。。");
// 接受客户端的连接
Socket s = ss.accept();
//获取客户端的IP和端口,并打印出来
String RemoteIP = s.getInetAddress().getHostAddress();
String RemotePort = ":" + s.getLocalPort();
System.out.println("A client come in!IP:" + RemoteIP
+ RemotePort);

// 得到接收的这个Socket的输入流,并封装成一个BufferedReader()
BufferedReader br = new BufferedReader(new InputStreamReader(s
.getInputStream()));

// 将从客户端接收到的数据再发送回客户端
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
String clientMsgString = br.readLine();
//服务器端控制台打印出接受到的消息
System.out.println("The Client Say:"+clientMsgString);
//向客户端问好
pw.println("Hello,"+clientMsgString+". Nice to meet you!");
// 关闭相应的资源
br.close();
pw.close();
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new Server().startServer();
}

}

Client端:

package com.hqh.hello.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
public void connServer() {
try {
// 建立与服务器端的链接
Socket s = new Socket("localhost", Server.SERVER_PORT);
System.out.println("Please enter Your Name and Press Enter key:");
// 监听键盘事件,等待用户输入字符串
Scanner sc = new Scanner(System.in);
// 得到Socket的输入流封装成一个PrintWriter
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
// 把用户输入的字符写出去
pw.println(sc.nextLine());

// 得到服务器端的输入流并封装成BufferedReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
System.out.println("服务器发送给我的数据:"+br.readLine());

} catch (UnknownHostException e) {
System.err.println("找不到你指定的主机!"+e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}

public static void main(String[] args) {
new Client().connServer();
}

}

测试结果:

1、首先运行Server类,控制台输出:等待客户端发起连接。。。

2、运行Client类,控制台提示:Please enter Your Name and Press Enter key:

同时服务器端输出:A client come in!IP:127.0.0.1:8888

3、输入你的名字回车:Please enter Your Name and Press Enter key:
千好

4、服务器端接收到客户端输入的字符:The Client Say:千好

5、客户端收到服务器端发来的问候:服务器发送给我的数据:Hello,千好. Nice to meet you!