java---socket编程之客户端代码

客户端主要是接收客户的输入,把服务器的输出显示出来等一些操作.每一个客户端就相当于一个个体,所需要实现的功能就是接受和发送
所遇到的问题:
1.textarea每次得到输出后滚动条不会自动下拉到最底端
2.怎么把界面绑定到socket操作里面
3.printwriter怎么输入
启动代码
package com.niuli;
/**
 * 客户端程序
 * 客户端的工作主要是对服务器端的读取和写入
 */
import java.awt.EventQueue;

import com.showwindow.Mainwindow;

public class startchat {

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Mainwindow frame = new Mainwindow();
                    frame.setVisible(true);
                    chatmanage.getinstance().setwindow(frame);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

socket操作代码:

package com.niuli;

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

import javax.swing.JOptionPane;

import com.showwindow.Mainwindow;

public class chatmanage {
    //单例化操作
    private chatmanage(){};
    private static final chatmanage chat = new chatmanage();
    public static chatmanage getinstance() {
        return chat;
    }

    Mainwindow mianwindow;//用于操作界面的函数
    Socket socket;
    String IP;
    BufferedReader reader;
    PrintWriter writer;

    public void setwindow(Mainwindow mainwindow) {
        this.mianwindow = mainwindow;
        mainwindow.append("文本框已经和界面绑定了!!!");
    }
    public void send(String line) {
        if (writer!=null) {
            //追加要带换行符
            writer.write(line +"\n");
            //flush强制刷新
            writer.flush();
        }else {
            mianwindow.append("当前连接已中断");
        }
    }
    public void connect(String ip) {
        IP = ip;
        new Thread(){
            public void run() {
                try {
                    socket = new Socket(IP, 12345);
                    reader = new BufferedReader(
                                new InputStreamReader(
                                        socket.getInputStream()));
                    writer = new PrintWriter(
                                            socket.getOutputStream());
                    String line;
                    while((line = reader.readLine())!=null){
                        mianwindow.append("收到:"+line);
                    }
                    reader.close();
                    writer.close();
                    reader = null;
                    writer = null;

                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            };

        }.start();
    }
}

swing界面代码

package com.showwindow;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextArea;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

import com.niuli.chatmanage;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Mainwindow extends JFrame {
    private static final long serialVersionUID = 1L;

    private JPanel contentPane;
    private JTextField ip;
    private JButton connectport;
    private JScrollPane scrollPane;
    private JTextArea textArea;
    private JTextField sendtext;
    private JButton send;



    /**
     * Create the frame.
     */
    public Mainwindow() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 543, 414);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        ip = new JTextField();
        ip.setText("127.0.0.1");
        ip.setColumns(10);

        connectport = new JButton("连接到服务器");
        connectport.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                chatmanage.getinstance().connect(ip.getText());
            }
        });

        scrollPane = new JScrollPane();
        //设置水平滚动条不在显示
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        sendtext = new JTextField();
        sendtext.setColumns(10);

        send = new JButton("发送");
        send.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                chatmanage.getinstance().send(sendtext.getText());
                append("我说:"+sendtext.getText());
                sendtext.setText("");
            }
        });
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.TRAILING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(ip, GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(connectport))
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(sendtext, GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(send, GroupLayout.PREFERRED_SIZE, 136, GroupLayout.PREFERRED_SIZE))
                .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE)
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                        .addComponent(ip, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                        .addComponent(connectport))
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
                        .addComponent(send)
                        .addComponent(sendtext, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
        );

        textArea = new JTextArea();
        textArea.setLineWrap(true);
        scrollPane.setViewportView(textArea);
        contentPane.setLayout(gl_contentPane);
    }
    public void append(String line) {
        textArea.append("\n"+line);
        //每次追加后使光标都显示到最后一行,然后滚动条会自动到最后一行
        textArea.setCaretPosition(textArea.getText().length());
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-08-03 13:54  牛李  阅读(608)  评论(0编辑  收藏  举报

导航