本程序使用网络编程的模拟聊天。
实现双方的通话需要双方为点对点的通信,即双方既是接收方也是发送方。
对应于程序,接收方为服务器套接字,发送方为客户端套接字。
须先启动程序1,然后在启动程序2.(因为程序1先作为服务器,服务器需先开启才能接受客户端的请求)。
接收方服务器套接字:ServerSocket serverSocket = new ServerSocket(端口号);
接收方监听客户端套接字:Socket socket = serverSocket.accept();
发送方套接字:Socket socket = new Socket(IP地址,端口号);
发送方与接受方的端口号应保持一致,且发送方的IP地址为接收方的IP的地址;
本机地址可由 ”localhost“ 或 127.0.0.1 获得。
程序1如下:
package javaIO;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Chat1{
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket socket = serverSocket.accept();
new Thread(()->conversation(socket)).start(); //创建线程处理连接的套接字
serverSocket.close();
} catch (Exception e) {
}
}
public static void conversation(Socket socket) {
try {
Socket socket2 = new Socket("localhost", 9000);
DataInputStream dataInputStream = new
DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new
DataOutputStream(socket2.getOutputStream());
Scanner input = new Scanner(System.in);
InetAddress inetAddress = socket2.getInetAddress();
System.out.println("现在开始与主机"+inetAddress.getHostName()+"对话,地址为:
"+inetAddress.getHostAddress());
String message = "";
do {
String text = dataInputStream.readUTF();
System.out.println(text);
System.out.print("输入信息: ");
message = input.nextLine();
dataOutputStream.writeUTF(message);
dataOutputStream.flush();
}while(!message.equals("拜"));
input.close();
dataOutputStream.close();
dataInputStream.close();
socket2.close();
} catch (Exception e) {
}
}
}
程序2如下:
package javaIO;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Chat2{
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
Socket socket = new Socket("localhost", 8000); //创建客户端套接字
DataOutputStream dataOutputStream = new
DataOutputStream(socket.getOutputStream());
InetAddress inetAddress = socket.getInetAddress();
System.out.println("现在开始与主机"+inetAddress.getHostName()+"对话,地址为:
"+inetAddress.getHostAddress());
ServerSocket serverSocket = new ServerSocket(9000);//创建服务器端套接字
Socket socket2 = serverSocket.accept(); //监听客户端套接字
DataInputStream dataInputStream = new
DataInputStream(socket2.getInputStream());
String text = "";
do {
System.out.print("输入信息: ");
text = input.nextLine();
dataOutputStream.writeUTF(text); //输出字符串
dataOutputStream.flush(); //清空数据(确保数据输出)
//输出读入的字符串
System.out.println(dataInputStream.readUTF());
}while(!text.equalsIgnoreCase("拜"));
input.close();//依次关闭对象
socket.close();
dataOutputStream.close();
serverSocket.close();
} catch (Exception e) {
}
}
}