Java中使用Socket实现聊天程序

作者:袖梨 2022-11-14

第一步:启动Server.java主程序。然后点击“Connect”按钮;

第二步:启动Client.java主程序。然后点击“Connect”按钮。

代码如下 复制代码

Server.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;


public class Server {
public static void initUIManager(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("获取系统外观失败:" + e);
}
}
public static void main(String[] args) {
initUIManager();
new ServerFrame();
}
}

class ServerFrame extends JFrame implements Runnable, ActionListener,KeyListener{
private static final long serialVersionUID = 1969584312152336324L;
JScrollPane textPane;
JTextArea areaText;
JTextField fieldMsg;
JButton butSend;
JButton butConnect;

ServerSocket socket;
Socket you;
DataInputStream in;
DataOutputStream out;
Thread thread;

public static int WIDTH = 500;
public static int HEIGHT = 400;
public static String title = "Server: 点击Connect后即可开始接受Client的请求";

public ServerFrame(){
init();
setTitle(title);
setSize(WIDTH,HEIGHT);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void init(){
setLayout(null);
areaText = new JTextArea();
areaText.setLineWrap(true);
textPane = new JScrollPane(areaText);

butSend = new JButton("Send");
fieldMsg = new JTextField(255);
butSend.addActionListener(this);
butConnect = new JButton("Connect");
butConnect.addActionListener(this);

textPane.setBounds(5, 5, WIDTH-25, HEIGHT-80);
fieldMsg.setBounds(5, HEIGHT-70, WIDTH-220, 24);
butSend.setBounds(WIDTH-195, HEIGHT-70, 80, 24);
butConnect.setBounds(WIDTH-100, HEIGHT-70, 80, 24);

fieldMsg.addKeyListener(this);

add(textPane);
add(butSend);
add(fieldMsg);
add(butConnect);
thread = new Thread();
}
public void startSocket(){
try{
areaText.append("Waiting for clients...n");
socket = new ServerSocket(4331);
you = socket.accept();
areaText.append("A Client is currently accepted by server... n");
in = new DataInputStream(you.getInputStream());
out = new DataOutputStream(you.getOutputStream());
if(!thread.isAlive()){
thread = new Thread(this);
}
thread.start();
}catch(Exception e){
System.out.println(e);
try {
socket = new ServerSocket(4331);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

public void send(){
String msg = fieldMsg.getText().trim();
if(msg.isEmpty()){
JOptionPane.showMessageDialog(this, "Please input you message before sending.");
return;
}
areaText.append("Server: " + msg + "n");
try{
out.writeUTF(msg);
}catch(Exception e){
e.printStackTrace();
}
}

@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==butSend){
send();
}
else if(arg0.getSource()==butConnect){
startSocket();
}
}
@Override
public void run() {
if(Thread.currentThread()==thread){
String msg = null;
while(true){
try{
msg = in.readUTF();
areaText.append("Client: " + msg + "n");
}catch(IOException e){
e.printStackTrace();
try {
socket = new ServerSocket(4331);
} catch (IOException e1) {
e1.printStackTrace();
}
break;
}
}
}
}

@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode()==KeyEvent.VK_ENTER){
send();
}
}

@Override
public void keyReleased(KeyEvent arg0) {

}

@Override
public void keyTyped(KeyEvent arg0) {

}

}

Client.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class Client {
public static void initUIManager(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("获取系统外观失败:" + e);
}
}

public static void main(String[] args) {
initUIManager();
new ClientFrame();
}
}

class ClientFrame extends JFrame implements Runnable, ActionListener,KeyListener{

private static final long serialVersionUID = 8518610966119429018L;

JScrollPane textPane;
JTextArea areaText;
JTextField fieldMsg;
JButton butSend;
JButton butConnect;

Socket socket;
DataInputStream in;
DataOutputStream out;

Thread thread;

public static int WIDTH = 500;
public static int HEIGHT = 400;
public static String title = "Client";

private static final String IP_ADDRESS = "127.0.0.1";

public ClientFrame(){
init();
setTitle(title);
setSize(WIDTH,HEIGHT);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void init(){
setLayout(null);
areaText = new JTextArea();
areaText.setLineWrap(true);
textPane = new JScrollPane(areaText);

butSend = new JButton("Send");
butSend.addKeyListener(this);
fieldMsg = new JTextField(255);
butSend.addActionListener(this);
butConnect = new JButton("Connect");
butConnect.addActionListener(this);

textPane.setBounds(5, 5, WIDTH-25, HEIGHT-80);
fieldMsg.setBounds(5, HEIGHT-70, WIDTH-220, 24);
butSend.setBounds(WIDTH-195, HEIGHT-70, 80, 24);
butConnect.setBounds(WIDTH-100, HEIGHT-70, 80, 24);

add(textPane);
add(butSend);
add(fieldMsg);
add(butConnect);

fieldMsg.addKeyListener(this);

socket = new Socket();
thread = new Thread(this);
}

public void startSocket(){
try{
if(!socket.isConnected()){
InetAddress address = InetAddress.getByName(IP_ADDRESS);
InetSocketAddress socketAddress = new InetSocketAddress(address,4331);
socket.connect(socketAddress);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
butSend.setEnabled(true);
if(!(thread.isAlive())){
thread = new Thread(this);
}
thread.start();
}
}catch(Exception e){
System.out.println(e);
socket = new Socket();
}
}

public void send(){
String msg = fieldMsg.getText().trim();
if(msg.isEmpty()){
JOptionPane.showMessageDialog(this, "Please input you message before sending.");
return;
}
areaText.append("Client: " + msg + "n");
try{
out.writeUTF(msg);
}catch(Exception e){
e.printStackTrace();
}
}

@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == butSend){
send();
}
else if(arg0.getSource() == butConnect){
startSocket();
}
}
@Override
public void run() {
if(Thread.currentThread() == thread){
String msg = null;
while(true){
try{
msg = in.readUTF();
areaText.append("Server: " + msg + "n");
}catch(IOException e){
e.printStackTrace();
socket = new Socket();
break;
}
}
}
}

@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode()==KeyEvent.VK_ENTER){
send();
}
}

@Override
public void keyReleased(KeyEvent arg0) {

}

@Override
public void keyTyped(KeyEvent arg0) {

}

}

相关文章

精彩推荐