本人也是一个初涉及编程的小白,今天尝试用socket编写一个类似与QQ的聊天窗口,分为客户端和服务器端,然后通过socket来通讯,废话不多说直接上代码:
首先是客户端:
Client.java
package myQQ;
import java.awt.FlowLayout;
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.InetSocketAddress;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.*;
public class Client extends JFrame implements Runnable, ActionListener{
private JTextArea chatArea;
private JTextField iptextField,porttextField,messageField;
private JButton connectionButton,sendButton;
private Socket socket;
private DataInputStream in;
private DataOutputStream out;
private Thread thread;
private JComboBox namecomboBox;
public Client(){
createUserInterface();
setTitle("客服端");
setSize(550,500);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createUserInterface(){
setLayout(new FlowLayout());
add(new JLabel("主机"));
iptextField=new JTextField(10);
add(iptextField);
add(new JLabel("端口"));
porttextField=new JTextField(10);
add(porttextField);
add(new JLabel("使用人"));
namecomboBox=new JComboBox();
namecomboBox.addItem("郑云红");
name