利用Scoket实现局域网通信
package org.example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ServerChat {
private int port =8888;
public ServerChat(int port){
this.port=port;
}
public ServerChat(){
}
public void service(){
try {
ServerSocket socket = new ServerSocket(port);
System.out.println("等待客户端连接...");
Socket socket1 = socket.accept();
System.out.println("一个客户端已连接!");
DataInputStream in = new DataInputStream(socket1.getInputStream());
DataOutputStream out = new DataOutputStream(socket1.getOutputStream());
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("请输入");
String send = scanner.nextLine();
out.writeUTF("服务端说:"+send);
String accept=in.readUTF();
System.out.println(accept);
}
} catch (IOException e) {
System.out.println("连接客户端失败!");
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new ServerChat().service();
}
}
package org.example;
import javax.swing.*;
import javax.xml.crypto.Data;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class ClientChat extends JFrame {
public ClientChat(){
}
private String host ="localhost";
private int port=8888;
public ClientChat(String host,int port){
this.host=host;
this.port=port;
}
public void chat(){
try {
Socket socket = new Socket(host,port);
System.out.println("连接成功!");
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in);
DataInputStream in = new DataInputStream(socket.getInputStream());
while (true){
System.out.println("请输入");
String send = scanner.nextLine();
out.writeUTF("客户端说:"+send);
String accept=in.readUTF();
System.out.println(accept);
}
} catch (IOException e) {
System.out.println("连接失败!");
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new ClientChat().chat();
}
}