基于TCP的客户端与服务器端之间的通信

使用说明:把服务器IP地址更改为自己的服务器主机IP地址即可


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JFrame;

public class Chat extends JFrame implements Runnable, ActionListener {

private Panel topPanel_1, downPanel_1, midPanel_left, midPanel_right;
private Label ipLabel, localNameLabel;
private TextField ipTextField, localNameField;
private Button createServer, searchServer, sendMessage;
private TextArea text1, text2, text3, text4;
private ServerSocket server;
private Socket serverSocket, clientSocket;
private DataOutputStream outputFromClient, outputFromServer;
private DataInputStream inputToClient, inputToServer;
private int scan = 2;// scan:便于区分0客户端与1服务器端的文本内容
private int lock=0;//0:创建服务器  1:停止服务器
/***************************** 获取主机IP 与 名称 ******************************/
public String getIp() {
    String ip = null;
    try {
        InetAddress myLocalHost = InetAddress.getLocalHost();
        ip = myLocalHost.getHostAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return ip;
}

public String getName() {
    String name = null;
    try {
        InetAddress myLocalHost = InetAddress.getLocalHost();
        name = myLocalHost.getHostName();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return name;
}

/***************************** 事件监听 *****************************/
public void message() {
    createServer.addActionListener(this);
    searchServer.addActionListener(this);
    sendMessage.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == createServer && lock==0) {
        text3.setText("");
        text3.append("服务器名称为:" + getName() + "\n");
        text3.append("服务器IP为:" + getIp() + "\n");
        text3.append("端口号为:6666\n");
        text3.append("服务器已经启动,正在监听.......\n");
        this.startServer();
        scan=1;
    } else if(e.getSource() == createServer && lock==1){
        try {
            serverSocket.close();
            text3.setText("");
            text3.append("服务器关闭成功");
            lock=0;
        } catch (IOException e1) {
            text3.append("服务器关闭异常");
            e1.printStackTrace();
        }           
    }else if (e.getSource() == searchServer) {
        text4.setText("");
        text4.append("正在搜索服务器,请稍等.....\n");
        this.startClient();
        scan=0;
    } else if (e.getSource() == sendMessage) {
        if (scan == 1) {// 服务器端
            try {
                outputFromServer = new DataOutputStream(
                        serverSocket.getOutputStream());
                String name = getName();
                if (text2.getText().length() > 0) {
                    text1.append(name + "说:   " + text2.getText()
                            + "\n");
                    outputFromServer.writeUTF(this.getName()+","+text2.getText());// 写入消息
                    text2.setText("");
                } else {
                    text2.setText("\n\n请输入内容\n\n");
                    Thread.sleep(1000);
                    text2.setText("");
                }
            } catch (InterruptedException | IOException e1) {
                e1.printStackTrace();
            }
        } else if (scan == 0 ) {// 客户端
            try {
                outputFromClient = new DataOutputStream(
                        clientSocket.getOutputStream());
                String name = getName();
                if (text2.getText().length() > 0 ) {
                    text1.append(name + "说:   " + text2.getText()+ "\n");
                    outputFromClient.writeUTF(this.getName()+","+text2.getText());// 写入消息
                    text2.setText("");
                } else if(text2.getText().length() <= 0) {
                    text2.setText("\n\n请输入内容\n\n");
                    Thread.sleep(1000);
                    text2.setText("");
                }
            } catch (InterruptedException | IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

/***************************** 启动服务器 *************************************/
public void startServer() {
    try {
        if(lock==0){
            server = new ServerSocket(6666);
            serverSocket = server.accept();
            createServer.setLabel("停止服务器");
            lock=1;
        }
    } catch (IOException e) {
        text3.setText("");
        text3.append("服务器启动错误,请重新设置后启动!\n可能是由于:\n");
        text3.append("1.端口被占用。\n");
        text3.append("2.服务器已经启动。\n");
        e.printStackTrace();
    }
}

/***************************** 启动客户端 *************************************/
public void startClient() {
    try {
        clientSocket = new Socket("192.168.31.125",6666);//更改为自己服务器主机的IP地址即可
        text4.append("连接成功 ");
        searchServer.setLabel("断开连接");
    } catch (Exception e) {
        text4.append("无法连接网络");
        e.printStackTrace();
    }
}

/******************************* 对话内容互相显示 *****************************/
public void messageDisplay() throws IOException {
    // 接收消息
    if (scan == 1) {// 客户端
        inputToClient = new DataInputStream(serverSocket.getInputStream());
        String receive = inputToClient.readUTF();
        String[] message=receive.split(",");
        text1.append(message[0]+"说:   "+message[1]+"\n");
    }else if(scan == 0){//服务器端
        inputToServer = new DataInputStream(clientSocket.getInputStream());
        String receive = inputToServer.readUTF();
        String[] message=receive.split(",");
        text1.append(message[0]+"说:   "+message[1]+"\n");
    }
}

/***************************** 创建主界面 *************************************/
private void launchFrame() {
    // /////////上面部分/////////////
    topPanel_1 = new Panel();
    ipLabel = new Label("IP地址");// 标签
    ipTextField = new TextField(getIp(), 19);
    localNameLabel = new Label("本机名称");
    localNameField = new TextField(getName(), 19);
    createServer = new Button("创建服务器");
    searchServer = new Button("搜索服务器");

    // /////////中部部分/////////////
    midPanel_left = new Panel();
    midPanel_right = new Panel();
    text1 = new TextArea(20, 68);
    text2 = new TextArea(3, 68);
    text3 = new TextArea(14, 25);
    text4 = new TextArea(9, 25);

    // /////////底部部分/////////////
    downPanel_1 = new Panel();
    sendMessage = new Button("发送");

    topPanel_1.add(ipLabel);// 加入面板
    topPanel_1.add(ipTextField);
    topPanel_1.add(localNameLabel);
    topPanel_1.add(localNameField);
    topPanel_1.add(createServer);
    topPanel_1.add(searchServer);

    midPanel_left.setLayout(new BorderLayout());
    midPanel_right.setLayout(new BorderLayout());
    midPanel_left.add(text1, BorderLayout.NORTH);
    midPanel_left.add(text2, BorderLayout.SOUTH);
    midPanel_right.add(text3, BorderLayout.NORTH);
    midPanel_right.add(text4, BorderLayout.SOUTH);

    downPanel_1.add(sendMessage);

    Container container = getContentPane();// 布局管理器
    container.setLayout(new BorderLayout());// 布局声明
    container.add(topPanel_1, BorderLayout.NORTH);
    container.add(midPanel_left, BorderLayout.CENTER);
    container.add(midPanel_right, BorderLayout.EAST);
    container.add(downPanel_1, BorderLayout.SOUTH);
    this.pack();// 调整此窗口的大小,以适合其子组件的首选大小和布局。
    setSize(700, 500);// 设置面板宽与高
    setTitle("点星光聊天");// 设置标题
    setResizable(false);// 大小不可变
    setVisible(true);// 设置面板可见
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭时释放资源
}

public static void main(String[] args) throws IOException {
    Chat chat = new Chat();
    chat.launchFrame();
    chat.message();
    while(true){
        chat.messageDisplay();
    }
}

@Override
public void run() {
    // TODO 自动生成的方法存根

}

}

你可能感兴趣的:(java,算法设计与数据结构)