JAVA写一网络聊天程序
- 格式:docx
- 大小:15.67 KB
- 文档页数:14
本科毕业论文(毕业设计)题目:局域网聊天软件系院:学生姓名:学号:专业:年级:完成日期:指导教师:摘要在网络越来越发达的今天,人们对网络的依赖越来越多,越来越离不开网络,由此而产生的聊天工具越来越多,例如,国外的ICQ、国内腾讯公司开发的OICQ。
基于Java网络编程的强大功能,本次毕业设计使用Java编写一个聊天系统。
一般来说,聊天工具大多数由客户端程序和服务器程序外加服务器端用于存放客户数据的数据库组成,本系统采用客户机/服务器架构模式通过Java提供的Socket类来连接客户机和服务器并使客户机和服务器之间相互通信,由于聊天是多点对多点的而Java提供的多线程功能用多线程可完成多点对多点的聊天,数据库管理系统用SQL Server2000完成并通过JDBC-ODBC桥访问数据库。
本系统建立在JAVA平台上,系统的设计使用了面向对象技术和面向对象的设计原则。
系统采用C/S结构,客户端与客户端以及客户端与服务器端之间通过Socket传送消息。
使用JAVA语言编写,开发工具采用Eclipse。
服务器端设计与实现过程中,采用了多线程技术,可以在单个程序当中同时运行多个不同的线程,执行不同的任务。
大大增强了程序对服务器资源的利用。
聊天系统完成后将可进行多人对多人的聊天,对好友进行添加、删除,对新用户的注册,发送消息、接受消息等等功能。
关键字:多线程;客户机/服务器;JA V A ;Socket ;Eclipse ;TCP/IPAbstractas the network become more and more developed, people become more and more lean to the network, and can not leave with out it. This caused the chat materials become more numerous, as the overseas ICQ system, the OICQ system that invented by Tencent Co., and so on. So we create a network chat medium just like the QQ.Java network programming based on the power, the use of Java designed to prepare graduates a chat system.In general, the majority of the chat tool for client and server program in addition to server-side storage of customer data for the database,the system uses a client / server architecture model the adoption of Java provided Socket class connect client and server and between the client and server communicate with each other, as the chat is to provide point-to-multipoint and multi-threaded Java function to be completed by using multi-threaded chat and more point-to-multipoint, database management system with SQL Server2000 the completion and adoption ofJDBC-ODBC Bridge access the database.The system built on the JAVA platform, the system design usingobject-oriented technology and object-oriented design principles. System uses the C / S structure, client and client-side and server-side client and send messages through Socket. The use of JAVA language, development tools using Eclipse. Design and Implementation of server-side process, the use of multi-threading technology, which can process in a single run at the same time a number of different threads, the implementation of different tasks. Procedures greatly enhanced the use of server resources.Chat system will allow people to complete chat to more friends,and the system can add, delete somebody,can deal with new user registration, send messages, receive messages and so on.Keywords : Multithreading ; Client/Server ;JA V A ;Socket ;Eclipse ;TCP/IP目录1 绪论 ......................................................................................................... 错误!未定义书签。
package com.wyh.chatRoom;import java.awt.BorderLayout;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import .InetAddress;import .ServerSocket;import .Socket;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTabbedPane;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.JToolBar;public class wyhChatRoom extends JFrame implements ActionListener{ private String name; //服务器聊天室的图形用户界面private JComboBox combox; //网名private JTextField text; //输入IP地址或域名的组合框private JTabbedPane tab; //选项卡窗格,每页与一个Socket通信public wyhChatRoom(int port ,String name) throws IOException{super("聊天室"+name+" "+InetAddress.getLocalHost()+"端口:"+port);this.setBounds(320, 240, 440, 240);this.setDefaultCloseOperation(EXIT_ON_CLOSE);JToolBar toolbar=new JToolBar(); //工具栏this.getContentPane().add(toolbar,"North");toolbar.add(new JLabel("主机"));combox=new JComboBox();combox.addItem("127.0.0.1");toolbar.add(combox);combox.setEditable(true);toolbar.add(new JLabel("端口"));text=new JTextField("1251");toolbar.add(text);JButton button_connect=new JButton("连接");button_connect.addActionListener(this);toolbar.add(button_connect);tab=new JTabbedPane(); //选项卡窗口this.setBackground(Color.blue);this.getContentPane().add(tab);this.setVisible(true);=name;while(true){Socket client=new ServerSocket(port).accept();//等待接受客户端的连接申请tab.addTab(name, new TabPageJPanel(client));//tab添加页,页中添加内部类面板tab.setSelectedIndex(tab.getTabCount()-1);//tab指定新页为选择状态port++;}}public void actionPerformed(ActionEvent e){if(e.getActionCommand()=="连接"){String host=(String)combox.getSelectedItem();int port=Integer.parseInt(text.getText());try{tab.addTab(name, new TabPageJPanel(new Socket(host,port)));//连接成功tab添加页tab.setSelectedIndex(tab.getTabCount()-1);//tab指定新页为选中状态}catch(IOException e1){e1.printStackTrace();}}}//面板内部类,每个对象表示选项卡窗格的一页,包含一个Socket和一个线程private class TabPageJPanel extends JPanel implements Runnable,ActionListener{Socket socket;Thread thread;JTextArea text_receiver;//显示对话内容的文本区JTextField text_sender; //输入发送内容的文本行JButton buttons[]; //发送‘离线’删除页按钮PrintWriter cout; //字符输出流对象int index;TabPageJPanel(Socket socket) {super(new BorderLayout());this.text_receiver=new JTextArea();this.text_receiver.setEditable(false);this.add(new JScrollPane(this.text_receiver));JPanel panel=new JPanel();this.add(panel,"South");this.text_sender=new JTextField(16);panel.add(this.text_sender);this.text_sender.addActionListener(this);String strs[]={"发送","离线","删除页"};buttons =new JButton[strs.length];for (int i = 0; i < buttons.length; i++) {buttons[i]=new JButton(strs[i]);panel.add(buttons[i]);buttons[i].addActionListener(this);}buttons[2].setEnabled(false);this.socket=socket;this.thread=new Thread(this);this.thread.start();}@Overridepublic void run() {try {this.cout =new PrintWriter(socket.getOutputStream(),true);this.cout.println(name);//发送自己网名给对方BufferedReader cin=new BufferedReader(new InputStreamReader(socket.getInputStream()));String name=cin.readLine(); //接收对方网名index=tab.getSelectedIndex();tab.setTitleAt(index, name);String aline=cin.readLine();while(aline!=null && !aline.equals("bye")){tab.setSelectedIndex(index);text_receiver.append(aline+"\r\n");Thread.sleep(1000);aline=cin.readLine();}cin.close();cout.close();socket.close();buttons[0].setEnabled(false);//接收方的发送按钮无效buttons[1].setEnabled(false);//接收方的离线按钮无效buttons[2].setEnabled(false);//接收方的删除按钮无效} catch (Exception e) {e.printStackTrace();}}@Overridepublic void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="发送"){this.cout.println(name+"说:"+text_sender.getText());text_receiver.append("我说:"+text_sender.getText()+"\n");text_sender.setText("");}if(e.getActionCommand()=="离线"){text_receiver.append("我离线\n");this.cout.println(name+"离线\n"+"bye");buttons[0].setEnabled(false);buttons[1].setEnabled(false);buttons[2].setEnabled(false);}}}public static void main(String[] args) throws IOException {new wyhChatRoom(2001, "航哥哥");//启动服务端,约定端口,指定网名}}。
摘要随着互联网的快速发展,网络聊天工具已经作为一种重要的信息交流工具,受到越来越多的网民的青睐.目前,出现了很多非常不错的聊天工具,其中应用比较广泛的有Netmeeting、腾讯QQ、MSN-Messager等等。
该系统开发主要包括一个网络聊天服务器程序和一个网络聊天客户程序两个方面。
前者通过Socket套接字建立服务器,服务器能读取、转发客户端发来信息,并能刷新用户列表。
后者通过与服务器建立连接,来进行客户端与客户端的信息交流。
其中用到了局域网通信机制的原理,通过直接继承Thread类来建立多线程。
开发中利用了计算机网络编程的基本理论知识,如TCP/IP协议、客户端/服务器端模式(Client/Server模式)、网络编程的设计方法等。
在网络编程中对信息的读取、发送,是利用流来实现信息的交换,其中介绍了对实现一个系统的信息流的分析,包含了一些基本的软件工程的方法。
经过分析这些情况,该局域网聊天工具采用Eclipse为基本开发环境和java 语言进行编写,首先可在短时间内建立系统应用原型,然后,对初始原型系统进行不断修正和改进,直到形成可行系统关键词:局域网聊天 socket javaAbstractAlong with the fast development of Internet,the network chating tool has already become one kind of important communication tools and received more and more web cams favor. At present, many extremely good chating tools have appeared . for example,Netmeeting, QQ,MSN—Messager and so on. This system development mainly includes two aspects of the server procedure of the network chat and the customer procedure of the network chat。
ChatClient.javaimport java.awt.*;import java.io.*;import .*;import java.applet.*;import java.util.Hashtable;public class ChatClient extends Applet implements Runnable{ Socket socket=null;DataInputStream in=null;//读取服务器端发来的消息DataOutputStream out=null;//向服务器端发送的消息InputInfo 用户名提交界面=null;UserChat 聊天界面=null;Hashtable listTable;//用于存放在线用户的用户名的散列表Label 提示条;Panel north,center;Thread thread;public void init(){setSize(1000,800);int width=getSize().width;int height=getSize().height;listTable=new Hashtable();setLayout(new BorderLayout());用户名提交界面=new InputInfo(listTable);int h=用户名提交界面.getSize().height;聊天界面=new UserChat("",listTable,width,height-(h+5));聊天界面.setVisible(false);提示条=new Label("正在连接到服务器...",Label.CENTER);提示条.setForeground(Color.red);north=new Panel(new FlowLayout(FlowLayout.LEFT));center=new Panel();north.add(用户名提交界面);north.add(提示条);center.add(聊天界面);add(north,BorderLayout.NORTH);add(center,BorderLayout.CENTER);validate();}public void start(){if(socket!=null&&in!=null&&out!=null){try{socket.close();in.close();out.close();聊天界面.setVisible(false);}catch(Exception ee){}}try{socket=new Socket(this.getCodeBase().getHost(),6666);in=new DataInputStream(socket.getInputStream());out=new DataOutputStream(socket.getOutputStream());}catch(IOException ee){提示条.setText("连接失败");}//客户端成功连接服务器端if(socket!=null){InetAddress address=socket.getInetAddress();提示条.setText("连接:"+address+"成功");用户名提交界面.setSocketConnection(socket,in,out);north.validate();}if(thread==null){thread=new Thread(this);thread.start();}}public void stop(){try{socket.close();thread=null;}catch(IOException e){this.showStatus(e.toString());}}public void run(){while(thread!=null){if(用户名提交界面.getchatornot()==true){聊天界面.setVisible(true);聊天界面.setName(用户名提交界面.getName());聊天界面.setSocketConnection(socket,in,out);提示条.setText("祝聊天快乐!");center.validate();break;}try{Thread.sleep(100);}catch(Exception e){}}}}ChatMain.javaimport .*;import java.util.*;public class ChatMain {public static void main(String args[]) {ServerSocket server=null;Socket you=null;Hashtable peopleList;peopleList=new Hashtable();while(true){try{//服务器端在端口6666处监听来自客户端的信息server=new ServerSocket(6666);}catch(IOException e1){System.out.println("正在监听");}try{//当服务器端接收到客户端的消息后,取得客户端的IP地址。
import java.io.*;import .*;import java.awt.*;import javax.swing.*;import java.awt.event.*;//引入包。
public class ChatClient {public static void main(String[] args) {ChatClient cc = new ChatClient();cc.receive();}JTextField jtf; // 文本条JTextArea jta; //文本域。
Socket s; //客户端PrintWriter out; //输出流BufferedReader in; //输入流public ChatClient() {JFrame frame = new JFrame("ChatClient");//窗口frame.setSize(400, 300); //大小jta = new JTextArea(); //文本域jta.setEditable(false); //不可编辑jtf = new JTextField();//文件条jtf.addActionListener(new ActionListener() { //添加监听。
public void actionPerformed(ActionEvent arg0) {send(); //调用send()方法}});frame.getContentPane().add(new JScrollPane(jta)); //添加滚动条frame.getContentPane().add(jtf, "South"); //添加文本条frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口。
frame.setVisible(true); //可显示的。
Java 多人聊天源码1.ChatApplet.java类import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import yout.*;import javax.swing.border.*;import java.io.*;import .*;public class ChatApplet extends JApplet {boolean isStandalone = false;BorderLayout borderLayout1 = new BorderLayout();Border border1;JPanel jPanel2 = new JPanel();Border border2;BorderLayout borderLayout2 = new BorderLayout();JPanel jPanel1 = new JPanel();JButton buttonSend = new JButton();BorderLayout borderLayout3 = new BorderLayout();JPanel jPanel3 = new JPanel();Border border3;BorderLayout borderLayout4 = new BorderLayout();JTextField textTalk = new JTextField();JPanel jPanel4 = new JPanel();Border border4;BorderLayout borderLayout5 = new BorderLayout();JScrollPane jScrollPane1 = new JScrollPane();JTextArea textMessages = new JTextArea();PrintWriter out = null;/**Get a parameter value*/public String getParameter(String key, String def) {return isStandalone ? System.getProperty(key, def) :(getParameter(key) != null ? getParameter(key) : def); }/**Construct the applet*/public ChatApplet() {}/**Initialize the applet*/public void init() {try {jbInit();Client client = new Client(this);if (client.isConnected())out = client.getOutputStream();elseappendMessage("大大的错误!!");}catch(Exception e) {e.printStackTrace();}}/**Component initialization*/private void jbInit() throws Exception {border1 = BorderFactory.createEmptyBorder(9,9,9,9);border2 = BorderFactory.createEmptyBorder(9,9,9,9);border3 = BorderFactory.createEmptyBorder(2,0,2,5);border4 = BorderFactory.createEmptyBorder(0,0,5,0);this.setSize(new Dimension(400,300));this.getContentPane().setLayout(borderLayout1);jPanel2.setBorder(border2);jPanel2.setLayout(borderLayout2);buttonSend.setFocusPainted(false);buttonSend.setText("发送");buttonSend.addActionListener(newjava.awt.event.ActionListener() {public void actionPerformed(ActionEvent e) {buttonSend_actionPerformed(e);}});jPanel1.setLayout(borderLayout3);jPanel3.setBorder(border3);jPanel3.setLayout(borderLayout4);jPanel4.setBorder(border4);jPanel4.setLayout(borderLayout5);textTalk.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(KeyEvent e) {textTalk_keyPressed(e);}});this.getContentPane().add(jPanel2, BorderLayout.CENTER);jPanel2.add(jPanel1, BorderLayout.SOUTH);jPanel1.add(buttonSend, BorderLayout.EAST);jPanel1.add(jPanel3, BorderLayout.CENTER);jPanel3.add(textTalk, BorderLayout.CENTER);jPanel2.add(jPanel4, BorderLayout.CENTER);jPanel4.add(jScrollPane1, BorderLayout.CENTER);jScrollPane1.getViewport().add(textMessages, null);}/**Get Applet information*/public String getAppletInfo() {return "Applet Information";}/**Get parameter info*/public String[][] getParameterInfo() {return null;}/**Main method*/public static void main(String[] args) {ChatApplet applet = new ChatApplet();applet.isStandalone = true;JFrame frame = new JFrame();//EXIT_ON_CLOSE == 3frame.setDefaultCloseOperation(3);frame.setTitle("Applet Frame");frame.getContentPane().add(applet, BorderLayout.CENTER);applet.init();applet.start();frame.setSize(400,320);Dimension d = Toolkit.getDefaultToolkit().getScreenSize();frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);frame.setVisible(true);}//static initializer for setting look & feelstatic {try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClass Name());}catch(Exception e) {}}public void appendMessage(String message) {textMessages.setText(message + textMessages.getText());}void buttonSend_actionPerformed(ActionEvent e) {String msg;msg = textTalk.getText().trim();if (msg.equals("") || msg == null) return;out.println(textTalk.getText());textTalk.setText("");}void textTalk_keyPressed(KeyEvent e) {if (e.getKeyChar() != '\n') return;out.println(textTalk.getText());textTalk.setText("");}}2.ChatServlet.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;public class ChatServlet extends HttpServlet {private static final String CONTENT_TYPE = "text/html";/**Initialize global variables*/public void init(ServletConfig config) throws ServletException { super.init(config);try {new Server();}catch (IOException ex) {System.err.println("IO 错误:");ex.printStackTrace(System.err);destroy();}/**Process the HTTP Get request*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType(CONTENT_TYPE);PrintWriter out = response.getWriter();out.println("<html>");out.println("<head><title>ChatServlet</title></head>");out.println("<body>");out.println("<p>The servlet has received a GET. This is the reply.</p>");out.println("</body></html>");}/**Clean up resources*/public void destroy() {}}3.Client.javaimport java.io.*;import .*;public class Client {Socket socket = null;private String host;private boolean connected = false;public boolean isConnected() { return connected; }public Client(ChatApplet applet) {try {host = applet.getDocumentBase().getHost();//host = "202.115.4.246";socket = new Socket(host, Server.port);connected = true;new ClientRecieveThread(socket, applet).start();}catch (Exception ex) {applet.appendMessage(ex.getMessage());ex.printStackTrace(System.err);}public PrintWriter getOutputStream() throws IOException {return new PrintWriter(socket.getOutputStream(), true);}}4.ClientRecieveThread.javaimport java.io.*;import .*;public class ClientRecieveThread extends Thread {private ChatApplet applet = null;private Socket socket = null;public ClientRecieveThread(Socket socket, ChatApplet applet) { this.socket = socket;this.applet = applet;}public void run() {BufferedReader in = null;String inputLine;try {in = new BufferedReader(new InputStreamReader(socket.getInputStream()));while ((inputLine = in.readLine()) != null) {//if (inputLine.equalsIgnoreCase("quit")) break; applet.appendMessage(inputLine + "\n");}}catch (Exception ex) {ex.printStackTrace(System.err);}finally {Close();}}void Close() {try {socket.close();catch (Exception ex) {ex.printStackTrace(System.err);}}}5.Protocol.javapublic class Protocol {private String userid;public Protocol(String userid) {erid = userid;}public String processInput(String input) {return (userid + ": " + input);}}6.Server.javaimport java.io.*;import .*;import java.util.Vector;public class Server {private ServerSocket serverSocket = null;public static int port = 4444;private boolean listening = true;Vector clientSockets = new Vector(10);public Server() throws IOException {try {serverSocket = new ServerSocket(port);}catch (Exception ex) {System.err.println("不能监听端口:" + port); ex.printStackTrace(System.err);System.exit(-1);System.out.println("成功监听端口:" + port);while (listening)addClient(serverSocket.accept());serverSocket.close();}public void addClient(Socket socket) throws IOException {new ServerThread(socket, this).start();clientSockets.add(socket);send("欢迎 " + socket.getInetAddress().getHostName() + " 来到这里!");System.out.println("聊天室共有 " + clientSockets.size() + " 人");}public void removeClient(Socket socket) throws IOException {send("欢送 " + socket.getInetAddress().getHostName() + " 的离去");clientSockets.remove(socket);System.out.println("聊天室共有 " + clientSockets.size() + " 人");}public void send(String msg) throws IOException {Socket socket = null;for (int I = 0; I < clientSockets.size(); I++) {socket = (Socket)(clientSockets.get(I));PrintWriter out = new PrintWriter(socket.getOutputStream(), true);out.println(msg);}}public static void main(String[] args) throws IOException {new Server();}}7.ServerThread.javapublic class ServerThread extends Thread {private Server server = null;private Socket socket = null;private Protocol jcp = null;private String userid;public ServerThread(Socket socket, Server server) {super("jetic Chat Server");this.socket = socket;this.server = server;userid = socket.getInetAddress().getHostName();jcp = new Protocol(userid);}public void run() {PrintWriter out = null;BufferedReader in = null;String inputLine, outputLine;try {out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));out.println("你可以开始你的闲聊了:)");while ((inputLine = in.readLine()) != null) {if (inputLine.equalsIgnoreCase("quit")) break;outputLine = jcp.processInput(inputLine);server.send(outputLine);}}catch (Exception ex) {ex.printStackTrace(System.err);Close();}finally {Close();}}private void Close() {try {server.removeClient(socket);socket.close();}catch (Exception ex) {ex.printStackTrace(System.err); }}}。
如何使用Java创建简单的网络应用程序1. 网络应用程序简介网络应用程序是一种通过互联网或局域网进行通信和数据交换的软件应用。
它可以基于客户端-服务器模型,也可以是对等模型。
Java是一种广泛使用的编程语言,具有优秀的网络编程能力,可以用于开发各种类型的网络应用程序。
2. Java网络编程基础Java提供了一系列标准类库和API,用于简化网络应用程序的开发。
其中最核心的类是包中的Socket和ServerSocket类。
Socket类代表一个客户端,可以向服务器发送请求和接收响应。
ServerSocket类则用于创建服务器端监听特定端口,并接受客户端的连接请求。
3. 创建简单的客户端首先,我们需要创建一个基本的客户端来连接服务器。
以下是一个使用Socket类创建简单客户端的示例代码:```javaimport java.io.IOException;import java.io.OutputStream;import .Socket;public class SimpleClient {public static void main(String[] args) {String serverAddress = "localhost";int serverPort = 8888;try (Socket socket = new Socket(serverAddress, serverPort)) { OutputStream outputStream = socket.getOutputStream(); String message = "Hello, Server!";byte[] bytes = message.getBytes();outputStream.write(bytes);outputStream.flush();} catch (IOException e) {e.printStackTrace();}}}```在该示例中,我们使用Socket类创建一个与服务器的连接,并获取输出流。
JAVA写一网络聊天程序JAVA写一网络聊天程序:要求:聊天室服务器、聊天室客户端;客户端之间可以聊天。
因为我是初级选手,想借此程序分析学习java,所以代码最好多一点注释...分数有限,望大家不吝赐教!!问题补充:需要图形用户界面哦,最好用swing组件服务器端:采用多线程,可以向客户广播:当前聊天室人数,客户名称列表,客户进入离开提示;客户端:可以设定昵称,性别,客户间可以私聊服务器端:import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;import .*;public class Server extends JFrame implements ActionListener{JPanel contentPane;JLabel jLabel2 = new JLabel();JTextField jTextField2 = new JTextField("4700");JButton jButton1 = new JButton();JLabel jLabel3 = new JLabel();JTextField jTextField3 = new JTextField();JButton jButton2 = new JButton();JScrollPane jScrollPane1 = new JScrollPane();JTextArea jTextArea1 = new JTextArea();ServerSocket server = null;Socket socket = null;BufferedReader instr =null;PrintWriter os=null ;//Construct the framepublic Server() {jbInit();}class MyThread extends Thread{//该线程负责接受数据public void run(){try{while(true){this.sleep(100);instr= new BufferedReader(newInputStreamReader(socket.getInputStream()));if(instr.ready()){ //检查是否有数据jTextArea1.append("客户端: "+instr.readLine()+"\n");}}}catch(Exception ex){}}}public void actionPerformed(ActionEvent e){if(e.getSource()==jButton1){int port=Integer.parseInt(jTextField2.getText().trim());listenClient(port);}if(e.getSource()==jButton2){String s=this.jTextField3.getText().trim();sendData(s);}}private void listenClient(int port){//侦听try{if(jButton1.getText().trim().equals("侦听")){server = new ServerSocket(port);jButton1.setText("正在侦听...");socket=server.accept();//等待,一直到客户端连接才望下执行sendData("已经成功连接。
");jButton1.setText("正在聊天...");jTextArea1.append("客户端已经连接到服务器\n"); MyThread t=new MyThread();t.start();}}catch(Exception ex){}}private void sendData(String s){//发送数据try{os= new PrintWriter(socket.getOutputStream());os.println(s);os.flush();if(!s.equals("已经成功连接。
"))this.jTextArea1.append("Server:"+s+"\n"); }catch(Exception ex){}}//Component initializationprivate void jbInit() {contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(null);this.setSize(new Dimension(540, 340));this.setTitle("服务器");jLabel2.setBounds(new Rectangle(22, 27, 72, 28));jLabel2.setText("端口号");jLabel2.setFont(new java.awt.Font("宋体", 0, 14)); jTextField2.setBounds(new Rectangle(113, 27, 315, 24));jButton1.setBounds(new Rectangle(440, 28, 73, 25));jButton1.setFont(new java.awt.Font("Dialog", 0, 14)); jButton1.setBorder(BorderFactory.createEtchedBorder()); jButton1.setActionCommand("jButton1");jButton1.setText("侦听");jLabel3.setBounds(new Rectangle(23, 57, 87, 28));jLabel3.setText("请输入信息");jLabel3.setFont(new java.awt.Font("宋体", 0, 14)); jTextField3.setBounds(new Rectangle(114, 60, 314, 24)); jTextField3.setText("");jButton2.setText("发送");jButton2.setActionCommand("jButton1");jButton2.setBorder(BorderFactory.createEtchedBorder()); jButton2.setFont(new java.awt.Font("Dialog", 0, 14)); jButton2.setBounds(new Rectangle(440, 58, 73, 25)); jScrollPane1.setBounds(new Rectangle(23, 92, 493, 189));contentPane.add(jTextField2, null);contentPane.add(jButton1, null);contentPane.add(jLabel3, null);contentPane.add(jTextField3, null);contentPane.add(jButton2, null);contentPane.add(jScrollPane1, null);contentPane.add(jLabel2, null);jScrollPane1.getViewport().add(jTextArea1, null);jButton1.addActionListener(this);jButton2.addActionListener(this);this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){try{socket.close();instr.close();System.exit(0);}catch(Exception ex){}}});}public static void main(String arg[]){ JFrame.setDefaultLookAndFeelDecorated(true); Server frm=new Server();frm.setVisible(true);}}客户端:import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.io.*;import .*;public class Client extends JFrame implements ActionListener{ JPanel contentPane;JLabel jLabel1 = new JLabel();JTextField jTextField1 = new JTextField("127.0.0.1"); JLabel jLabel2 = new JLabel();JTextField jTextField2 = new JTextField("4700"); JButton jButton1 = new JButton();JLabel jLabel3 = new JLabel();JTextField jTextField3 = new JTextField();JButton jButton2 = new JButton();JScrollPane jScrollPane1 = new JScrollPane();JTextArea jTextArea1 = new JTextArea();BufferedReader instr =null;Socket socket = null;PrintWriter os=null;public Client() {jbInit();}class MyThread extends Thread{public void run(){try{os=new PrintWriter(socket.getOutputStream());instr=new BufferedReader(new InputStreamReader(socket.getInputStream()));while(true){this.sleep(100);if(instr.ready()){jTextArea1.append("服务器: "+instr.readLine()+"\n");}}}catch(Exception ex){}}}public void actionPerformed(ActionEvent e){if(e.getSource()==jButton1){String ip=jTextField3.getText().trim();int port=Integer.parseInt(jTextField2.getText().trim()); connectServer(ip,port);}if(e.getSource()==jButton2){String s=this.jTextField3.getText().trim();sendData(s);}}private void connectServer(String ip,int port){//连接try{if(jButton1.getText().trim().equals("连接")){ jButton1.setText("连接服务器..."); socket=new Socket(ip,port);jButton1.setText("正在聊天");MyThread t=new MyThread();t.start();}}catch(Exception ex){}}private void sendData(String s){//发送数据try{os = new PrintWriter(socket.getOutputStream());os.println(s);os.flush();this.jTextArea1.append("Server:"+s+"\n");}catch(Exception ex){}}private void jbInit() {contentPane = (JPanel) this.getContentPane();jLabel1.setFont(new java.awt.Font("宋体", 0, 14)); jLabel1.setText("服务器名称");jLabel1.setBounds(new Rectangle(20, 22, 87, 28)); contentPane.setLayout(null);this.setSize(new Dimension(540, 340));this.setTitle("客户端");jTextField1.setBounds(new Rectangle(114, 26, 108, 24));jLabel2.setBounds(new Rectangle(250, 25, 72, 28));jLabel2.setText("端口号");jLabel2.setFont(new java.awt.Font("宋体", 0, 14)); jTextField2.setBounds(new Rectangle(320, 27, 108, 24));jButton1.setBounds(new Rectangle(440, 28, 73, 25));jButton1.setFont(new java.awt.Font("Dialog", 0, 14)); jButton1.setBorder(BorderFactory.createEtchedBorder()); jButton1.setActionCommand("jButton1");jButton1.setText("连接");jLabel3.setBounds(new Rectangle(23, 57, 87, 28));jLabel3.setText("请输入信息");jLabel3.setFont(new java.awt.Font("宋体", 0, 14)); jTextField3.setBounds(new Rectangle(114, 60, 314, 24));jButton2.setText("发送");jButton2.setActionCommand("jButton1");jButton2.setBorder(BorderFactory.createEtchedBorder());jButton2.setFont(new java.awt.Font("Dialog", 0, 14)); jButton2.setBounds(new Rectangle(440, 58, 73, 25)); jScrollPane1.setBounds(new Rectangle(23, 92, 493, 189));contentPane.add(jLabel1, null);contentPane.add(jTextField1, null);contentPane.add(jLabel2, null);contentPane.add(jTextField2, null);contentPane.add(jButton1, null);contentPane.add(jLabel3, null);contentPane.add(jTextField3, null);contentPane.add(jButton2, null);contentPane.add(jScrollPane1, null);jScrollPane1.getViewport().add(jTextArea1, null);jButton1.addActionListener(this);jButton2.addActionListener(this);this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){try{socket.close();instr.close();os.close();System.exit(0); }catch(Exception ex){}}});}public static void main(String arg[]){JFrame.setDefaultLookAndFeelDecorated(true); Client frm=new Client();frm.setVisible(true);}}先启动服务器端,侦听端口,再启动客户端,就行了。