基于java Swing测TCP Socket 实例

最近闲来无事,复习了java相关的基础知识,重点是java io流以及多线程,基于之前常用QT 开发pc程序,所以就想用java Swing巩固下基础知识。

整个Demo基于Tcp Socket通信,包括server和多Client端,基础代码,以做以后笔记之用。


Server端代码:

/*
 * Form1.java
 *
 * Created on __DATE__, __TIME__
 */

package com.deyuan.io.form;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author __USER__
 */
public class Server extends javax.swing.JFrame {

	public static List getSocketList() {
		return socketList;
	}

	public static void setSocketList(List socketList) {
		Server.socketList = socketList;
	}

	public javax.swing.JButton getjButton1() {
		return jButton1;
	}

	public void setjButton1(javax.swing.JButton jButton1) {
		this.jButton1 = jButton1;
	}

	public javax.swing.JButton getjButton2() {
		return jButton2;
	}

	public void setjButton2(javax.swing.JButton jButton2) {
		this.jButton2 = jButton2;
	}

	public javax.swing.JLabel getjLabel1() {
		return jLabel1;
	}

	public void setjLabel1(javax.swing.JLabel jLabel1) {
		this.jLabel1 = jLabel1;
	}

	public javax.swing.JScrollPane getjScrollPane1() {
		return jScrollPane1;
	}

	public void setjScrollPane1(javax.swing.JScrollPane jScrollPane1) {
		this.jScrollPane1 = jScrollPane1;
	}

	public javax.swing.JScrollPane getjScrollPane2() {
		return jScrollPane2;
	}

	public void setjScrollPane2(javax.swing.JScrollPane jScrollPane2) {
		this.jScrollPane2 = jScrollPane2;
	}

	public javax.swing.JTextArea getjTextArea1() {
		return jTextArea1;
	}

	public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
		this.jTextArea1 = jTextArea1;
	}

	public javax.swing.JTextArea getjTextArea2() {
		return jTextArea2;
	}

	public void setjTextArea2(javax.swing.JTextArea jTextArea2) {
		this.jTextArea2 = jTextArea2;
	}

	public javax.swing.JTextField getjTextField1() {
		return jTextField1;
	}

	public void setjTextField1(javax.swing.JTextField jTextField1) {
		this.jTextField1 = jTextField1;
	}

	public java.awt.Label getLabel1() {
		return label1;
	}

	public void setLabel1(java.awt.Label label1) {
		this.label1 = label1;
	}

	public java.awt.Label getLabel2() {
		return label2;
	}

	public void setLabel2(java.awt.Label label2) {
		this.label2 = label2;
	}

	public javax.swing.JTextArea getjTextArea3() {
		return jTextArea3;
	}

	public void setjTextArea3(javax.swing.JTextArea jTextArea3) {
		this.jTextArea3 = jTextArea3;
	}

	public javax.swing.JLabel getjLabel2() {
		return jLabel2;
	}

	public void setjLabel2(javax.swing.JLabel jLabel2) {
		this.jLabel2 = jLabel2;
	}

	public javax.swing.JScrollPane getjScrollPane3() {
		return jScrollPane3;
	}

	public void setjScrollPane3(javax.swing.JScrollPane jScrollPane3) {
		this.jScrollPane3 = jScrollPane3;
	}

	public Thread getT1() {
		return t1;
	}

	public void setT1(Thread t1) {
		this.t1 = t1;
	}

	public Boolean getFlag() {
		return flag;
	}

	public void setFlag(Boolean flag) {
		this.flag = flag;
	}

	/** Creates new form Form1 */
	public Server() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jTextField1 = new javax.swing.JTextField();
		jLabel1 = new javax.swing.JLabel();
		jButton1 = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jScrollPane2 = new javax.swing.JScrollPane();
		jTextArea2 = new javax.swing.JTextArea();
		jButton2 = new javax.swing.JButton();
		label1 = new java.awt.Label();
		label2 = new java.awt.Label();
		jScrollPane3 = new javax.swing.JScrollPane();
		jTextArea3 = new javax.swing.JTextArea();
		jLabel2 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setText("\u7aef\u53e3");

		jButton1.setText("\u7ed1\u5b9a");
		jButton1.setName("bindButton");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					bindPort(evt);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		jTextArea1.setColumns(20);
		jTextArea1.setEditable(false);
		jTextArea1.setRows(5);
		jScrollPane1.setViewportView(jTextArea1);

		jTextArea2.setColumns(20);
		jTextArea2.setRows(5);
		jScrollPane2.setViewportView(jTextArea2);

		jButton2.setText("\u53d1\u9001");
		jButton2.setName("sendButton");
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					bindSend(evt);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		label1.setFont(new java.awt.Font("宋体", 1, 18));
		label1.setText("\u63a5\u6536");

		label2.setFont(new java.awt.Font("宋体", 1, 18));
		label2.setText("\u53d1\u9001");

		jTextArea3.setColumns(20);
		jTextArea3.setForeground(new java.awt.Color(255, 255, 255));
		jTextArea3.setRows(5);
		jTextArea3.setEnabled(false);
		jScrollPane3.setViewportView(jTextArea3);

		jLabel2.setFont(new java.awt.Font("宋体", 1, 18));
		jLabel2.setText("\u65e5\u5fd7");

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				setFlag(false);
				t1.stop();
				try {
					server.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		});

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								layout
										.createSequentialGroup()
										.add(27, 27, 27)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				jLabel1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				39,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																		.add(
																				35,
																				35,
																				35)
																		.add(
																				jTextField1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				127,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																		.add(
																				49,
																				49,
																				49)
																		.add(
																				jButton1))
														.add(
																label1,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
														.add(
																jScrollPane1,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																346,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
										.add(80, 80, 80)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createParallelGroup(
																				org.jdesktop.layout.GroupLayout.TRAILING)
																		.add(
																				org.jdesktop.layout.GroupLayout.LEADING,
																				jScrollPane3,
																				org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																				353,
																				Short.MAX_VALUE)
																		.add(
																				org.jdesktop.layout.GroupLayout.LEADING,
																				layout
																						.createSequentialGroup()
																						.add(
																								jScrollPane2,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								278,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																						.addPreferredGap(
																								org.jdesktop.layout.LayoutStyle.UNRELATED)
																						.add(
																								jButton2,
																								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																								63,
																								Short.MAX_VALUE))
																		.add(
																				org.jdesktop.layout.GroupLayout.LEADING,
																				label2,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				jLabel2)
																		.addPreferredGap(
																				org.jdesktop.layout.LayoutStyle.RELATED,
																				315,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
										.add(62, 62, 62)));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								org.jdesktop.layout.GroupLayout.TRAILING,
								layout
										.createSequentialGroup()
										.add(33, 33, 33)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING)
																						.add(
																								layout
																										.createSequentialGroup()
																										.add(
																												layout
																														.createParallelGroup(
																																org.jdesktop.layout.GroupLayout.BASELINE)
																														.add(
																																jTextField1,
																																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																																31,
																																Short.MAX_VALUE)
																														.add(
																																jButton1))
																										.add(
																												38,
																												38,
																												38))
																						.add(
																								jLabel1,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								27,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
																		.add(
																				23,
																				23,
																				23))
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				64,
																				64,
																				64)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.TRAILING)
																						.add(
																								jLabel2)
																						.add(
																								label1,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
																		.add(
																				7,
																				7,
																				7)))
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																org.jdesktop.layout.GroupLayout.TRAILING,
																layout
																		.createSequentialGroup()
																		.add(
																				jScrollPane3,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				178,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				org.jdesktop.layout.LayoutStyle.RELATED)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING)
																						.add(
																								layout
																										.createSequentialGroup()
																										.add(
																												label2,
																												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												org.jdesktop.layout.LayoutStyle.RELATED)
																										.add(
																												jScrollPane2,
																												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																												142,
																												Short.MAX_VALUE))
																						.add(
																								org.jdesktop.layout.GroupLayout.TRAILING,
																								jButton2,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								53,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
														.add(
																jScrollPane1,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																365,
																Short.MAX_VALUE))
										.add(26, 26, 26)));

		pack();
	}// </editor-fold>

	// GEN-END:initComponents

	private void bindPort(java.awt.event.ActionEvent evt) throws IOException {
		// TODO add your handling code here:

		flag = true;
		String text = jTextField1.getText();

		int port = Integer.parseInt(text);

		// SocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(),
		// port);

		server = new ServerSocket(port);

		// server.bind(sa);

		t1 = new Thread(new ServerThread(server, this));

		t1.start();

	}

	private void bindSend(java.awt.event.ActionEvent evt) throws IOException {
		// TODO add your handling code here:

		String receive = jTextArea2.getText();
		for (int i = 0; i < socketList.size(); i++) {
			Socket socket = (Socket) socketList.get(i);
			if (!socket.isClosed()) {
				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
						socket.getOutputStream()));
				out.write(receive);
				out.flush();
			}

		}

	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Server().setVisible(true);
			}
		});
	}

	public static List socketList = new ArrayList();

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JTextArea jTextArea1;
	private javax.swing.JTextArea jTextArea2;
	private javax.swing.JTextArea jTextArea3;
	private javax.swing.JTextField jTextField1;
	private java.awt.Label label1;
	private java.awt.Label label2;

	private Thread t1 = null;
	private ServerSocket server = null;
	private Boolean flag = true;
	// End of variables declaration//GEN-END:variables

}

Server端绑定端口之后,就开始起线程监听有无Client端接入,一旦有客户端接入之后,起线程处理,之前QT关于子线程通知主线程也即UI线程更新界面,有很好的机制,看了下Swing也有SwingUtilities.invokeLater可以实现没具体API以及功能自行百度。


ServerThread:

package com.deyuan.io.form;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.SwingUtilities;

public class ServerThread implements Runnable {

	private ServerSocket server = null;

	private Server server1 = null;

	public ServerThread(ServerSocket server, Server server1) {

		this.server = server;
		this.server1 = server1;

	}

	@SuppressWarnings( { "unchecked", "static-access" })
	public void run() {
		// TODO Auto-generated method stub

		while (true) {
			Socket socket = null;
			try {
				socket = server.accept();
				final String address = socket.getRemoteSocketAddress()
						.toString();
				final int port = socket.getPort();

				server1.getSocketList().add(socket);

				SwingUtilities.invokeLater(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub

						server1.getjTextArea3().append(
								"有新客户端接入,对方IP:" + address + ",端口:" + port
										+ "\r\n");

					}
				});

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Thread thread = new Thread(new ServerHandleThread(socket, server1));
			thread.start();

		}

	}
}


ServerHandleThread:

package com.deyuan.io.form;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import javax.swing.SwingUtilities;

public class ServerHandleThread implements Runnable {

	private Socket socket = null;
	private Server server = null;

	public ServerHandleThread(Socket socket, Server server) {

		this.socket = socket;
		this.server = server;

	}

	public void run() {
		// TODO Auto-generated method stub

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		char[] chars = new char[1024];
		int length = 0;

		try {
			while (server.getFlag() && (length = in.read(chars)) != -1) {
				final String str = new String(chars, 0, length);
				SwingUtilities.invokeLater(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub

						server.getjTextArea1().append(str);

					}
				});
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}


客户端:

/*
 * Client.java
 *
 * Created on __DATE__, __TIME__
 */

package com.deyuan.io.form;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

/**
 * 
 * @author __USER__
 */
public class Client extends javax.swing.JFrame {

	/** Creates new form Client */
	public Client() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jTextField1 = new javax.swing.JTextField();
		jLabel2 = new javax.swing.JLabel();
		jTextField2 = new javax.swing.JTextField();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jScrollPane2 = new javax.swing.JScrollPane();
		jTextArea2 = new javax.swing.JTextArea();
		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();
		jButton3 = new javax.swing.JButton();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jLabel1.setText("IP");

		jTextField1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField1ActionPerformed(evt);
			}
		});

		jLabel2.setText("\u7aef\u53e3");

		jTextField2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField2ActionPerformed(evt);
			}
		});

		jTextArea1.setColumns(20);
		jTextArea1.setRows(5);
		jScrollPane1.setViewportView(jTextArea1);

		jTextArea2.setColumns(20);
		jTextArea2.setRows(5);
		jScrollPane2.setViewportView(jTextArea2);

		jButton1.setText("\u53d1\u9001");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					jButton1ActionPerformed(evt);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		jButton2.setText("\u8fde\u63a5");
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					clientServer(evt);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		jButton3.setText("\u65ad\u5f00");
		jButton3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					disConnect(evt);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		jLabel3.setText("\u53d1\u9001");

		jLabel4.setText("\u63a5\u6536");

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				if (socket.isConnected()) {
					flag = false;
					try {
						socket.close();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					thread1.stop();

				}
			}
		});

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								layout
										.createSequentialGroup()
										.add(25, 25, 25)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				jLabel1)
																		.add(
																				26,
																				26,
																				26)
																		.add(
																				jTextField1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				138,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				11,
																				11,
																				11)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING)
																						.add(
																								jLabel3)
																						.add(
																								jScrollPane1,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								243,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
										.add(30, 30, 30)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				jLabel2)
																		.add(
																				36,
																				36,
																				36)
																		.add(
																				jTextField2,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				91,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																		.add(
																				46,
																				46,
																				46)
																		.add(
																				jButton2)
																		.add(
																				18,
																				18,
																				18)
																		.add(
																				jButton3))
														.add(
																org.jdesktop.layout.GroupLayout.TRAILING,
																layout
																		.createSequentialGroup()
																		.add(
																				22,
																				22,
																				22)
																		.add(
																				jButton1)
																		.addPreferredGap(
																				org.jdesktop.layout.LayoutStyle.RELATED,
																				57,
																				Short.MAX_VALUE)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING)
																						.add(
																								jLabel4)
																						.add(
																								jScrollPane2,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								232,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
										.addContainerGap()));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								layout
										.createSequentialGroup()
										.add(44, 44, 44)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.BASELINE)
														.add(jLabel1)
														.add(
																jTextField1,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
														.add(
																jTextField2,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
														.add(jLabel2).add(
																jButton2).add(
																jButton3))
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				18,
																				18,
																				18)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.BASELINE)
																						.add(
																								jLabel3)
																						.add(
																								jLabel4))
																		.add(
																				5,
																				5,
																				5)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.TRAILING)
																						.add(
																								org.jdesktop.layout.GroupLayout.LEADING,
																								jScrollPane2,
																								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																								242,
																								Short.MAX_VALUE)
																						.add(
																								org.jdesktop.layout.GroupLayout.LEADING,
																								jScrollPane1,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																								242,
																								org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
																		.add(
																				36,
																				36,
																				36))
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				145,
																				145,
																				145)
																		.add(
																				jButton1)
																		.addContainerGap()))));

		pack();
	}// </editor-fold>

	// GEN-END:initComponents

	private void disConnect(java.awt.event.ActionEvent evt) throws IOException {
		// TODO add your handling code here:

		if (socket.isConnected()) {
			flag = false;
			socket.close();
			thread1.stop();

		}

	}

	private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	private void clientServer(java.awt.event.ActionEvent evt)
			throws NumberFormatException, UnknownHostException, IOException {

		String sip = jTextField1.getText();
		String sport = jTextField2.getText();

		try {
			socket = new Socket(sip, Integer.parseInt(sport));

		} catch (java.net.UnknownHostException e) {
			JOptionPane.showMessageDialog(null, "连接服务端出错,请检查连接地址和端口", "提示",
					JOptionPane.ERROR_MESSAGE);
			return;
		} catch (java.io.IOException e) {
			JOptionPane.showMessageDialog(null, "连接服务端出错,请检查服务端是否开启", "提示",
					JOptionPane.ERROR_MESSAGE);
			return;
		}

		flag = true;

		ClientThread t = new ClientThread(socket, this);

		thread1 = new Thread(t);

		thread1.start();

	}

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
			throws IOException {
		// TODO add your handling code here:

		if (socket.isClosed())
			return;
		String text = jTextArea1.getText();
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket
				.getOutputStream()));
		out.write(text);
		out.flush();

		// socket.shutdownOutput();
		// socket.close();

	}

	private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Client().setVisible(true);
			}
		});
	}

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JButton jButton3;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JTextArea jTextArea1;
	private javax.swing.JTextArea jTextArea2;
	private javax.swing.JTextField jTextField1;
	private javax.swing.JTextField jTextField2;
	// End of variables declaration//GEN-END:variables
	private Socket socket = null;

	private Thread thread1 = null;

	private boolean flag = true;

	public javax.swing.JButton getjButton1() {
		return jButton1;
	}

	public void setjButton1(javax.swing.JButton jButton1) {
		this.jButton1 = jButton1;
	}

	public javax.swing.JButton getjButton2() {
		return jButton2;
	}

	public void setjButton2(javax.swing.JButton jButton2) {
		this.jButton2 = jButton2;
	}

	public javax.swing.JButton getjButton3() {
		return jButton3;
	}

	public void setjButton3(javax.swing.JButton jButton3) {
		this.jButton3 = jButton3;
	}

	public javax.swing.JLabel getjLabel1() {
		return jLabel1;
	}

	public void setjLabel1(javax.swing.JLabel jLabel1) {
		this.jLabel1 = jLabel1;
	}

	public javax.swing.JLabel getjLabel2() {
		return jLabel2;
	}

	public void setjLabel2(javax.swing.JLabel jLabel2) {
		this.jLabel2 = jLabel2;
	}

	public javax.swing.JScrollPane getjScrollPane1() {
		return jScrollPane1;
	}

	public void setjScrollPane1(javax.swing.JScrollPane jScrollPane1) {
		this.jScrollPane1 = jScrollPane1;
	}

	public javax.swing.JScrollPane getjScrollPane2() {
		return jScrollPane2;
	}

	public void setjScrollPane2(javax.swing.JScrollPane jScrollPane2) {
		this.jScrollPane2 = jScrollPane2;
	}

	public javax.swing.JTextArea getjTextArea1() {
		return jTextArea1;
	}

	public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
		this.jTextArea1 = jTextArea1;
	}

	public javax.swing.JTextArea getjTextArea2() {
		return jTextArea2;
	}

	public void setjTextArea2(javax.swing.JTextArea jTextArea2) {
		this.jTextArea2 = jTextArea2;
	}

	public javax.swing.JTextField getjTextField1() {
		return jTextField1;
	}

	public void setjTextField1(javax.swing.JTextField jTextField1) {
		this.jTextField1 = jTextField1;
	}

	public javax.swing.JTextField getjTextField2() {
		return jTextField2;
	}

	public void setjTextField2(javax.swing.JTextField jTextField2) {
		this.jTextField2 = jTextField2;
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

}

客户端绑定IP和端口之后,起线程读数据。


ClientThread:


package com.deyuan.io.form;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class ClientThread implements Runnable {

	private Socket socket = null;
	private Client client = null;

	public ClientThread(Socket socket, Client client) {

		this.socket = socket;
		this.client = client;

	}

	public void run() {
		// TODO Auto-generated method stub

		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		char[] chars = new char[1024];
		int length = 0;

		try {
			while ((client.isFlag()) && (length = in.read(chars)) != -1) {
				final String content = new String(chars, 0, length);

				SwingUtilities.invokeLater(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub
						client.getjTextArea2().append(content);
					}
				});

			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block

			JOptionPane.showMessageDialog(null, "服务端断开,请重新连接", "提示",
					JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}



参与评论 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

110成成

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值