1.服务端的代码:
package Day1209;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
//服务端
public static void testServer() {
System.out.println("等待客户端连接...");
//null=赋初值(开辟内容空间)
ServerSocket ss = null;//创建一个socket服务端,用于接受socket请求
Scanner keybordInput = null;//键盘输入流 Scanner:扫描器
Scanner socketInput = null;//网络输入流
PrintWriter socketOutput = null;//网络输出流
try {
//发布一个端口
ss = new ServerSocket(8083);
//创建一个接收链接客户端的对象
Socket socket = ss.accept();
System.out.println(socket.getInetAddress()+"已成功连接到此台服务器上.");
//字段输出流
socketOutput = new PrintWriter(socket.getOutputStream());
socketOutput.println("已成功连接到远程服务器!" + "\t" + "请您先发言。");
socketOutput.flush();//把打印的内容"冲"出去,即是发出去
keybordInput = new Scanner(System.in);//扫描系统(键盘)
socketInput = new Scanner(socket.getInputStream());//声明一个网络输入
// 阻塞等待客户端发送消息过来
while(socketInput.hasNextLine()){//设定循环,当网络输入流有下一行时执行循环
String indata = socketInput.nextLine();//每次读取网络输入流数据的下一行数据
System.out.println("客户端:" + indata);//打印
System.out.print("我(服务端):");//站位显示效果
String keyborddata = keybordInput.nextLine();//键盘输入的下一行数据读取
socketOutput.println(keyborddata);//打印键盘输入数据流数据
socketOutput.flush();//发送字节数据流
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
socketOutput.close();
keybordInput.close();
socketInput.close();
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
testServer();
}
}
2.客户端的代码:
package Day1209;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void testClient() {
System.out.println("正在向服务器请求连接...");
//socket:网络链接对象,即TCP封装成的对象
Socket socket = null;
//键盘输入流
Scanner keybordInput = null;
//网络输入流
Scanner socketInput = null;
//网络输出流
PrintWriter socketOutput = null;
try {
socket = new Socket("127.0.0.1",8083);
socketInput = new Scanner(socket.getInputStream());
System.out.println(socketInput.nextLine());
socketOutput = new PrintWriter(socket.getOutputStream());
//先读取键盘录入方可向服务端发送消息
System.out.print("我(客户端):");
keybordInput = new Scanner(System.in);
while (keybordInput.hasNextLine()) {
//键盘输入内容,写到服务端的的控制台
String keyborddata = keybordInput.nextLine();
socketOutput.println(keyborddata);
socketOutput.flush();
//阻塞等待接收服务端的消息
String indata = socketInput.nextLine();
System.out.println("我(服务端)"+indata);
System.out.print("我(客户端):");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
keybordInput.close();
socketOutput.close();
socketInput.close();
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
testClient();
}
}
网友评论