上个周五的下午,在公司闲来无事,
写了个小程序玩玩,
稍微测试了一下,居然能用!
但由于代码量较少,也谈不上什么设计,
发上来算是个备忘吧:
服务器端程序:
packagecom.test.talk;importjava.awt.BorderLayout;importjava.awt.FlowLayout; importjava.awt.
event.ActionEvent; importjava.awt.
event.ActionListener; importjava.awt.
event.WindowAdapter; importjava.awt.
event.WindowEvent; importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.BindException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.LinkedList;importjava.util.List;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.JTextField;
publicclassServerextendsJFrame { booleanstarted=
false;
privateServerSocketss=
null;
privateListclientList=
newLinkedList();
privateJLabelportLbl=
null;
privateJTextFieldportTxt=
null;
privateJButtonportSetBtn=
null;
privateStringport=
null;
privateJButtonstartBtn=
null;
privateJButtonstopBtn=
null;
privateJPanelmainPanle=
null;
privateJPanelheadPanle=
null;
publicstaticvoidmain(String[]args) {
newServer(); }
publicServer() { headPanle=
newJPanel(
newFlowLayout(FlowLayout.LEFT)); portLbl=
newJLabel(
"PORT"); portTxt=
newJTextField(7); portSetBtn=
newJButton(
"OK"); portSetBtn.addActionListener(
newActionListener() {
publicvoidactionPerformed(ActionEvente) {
if(portTxt.getText().matches(
"//d+")) {port=portTxt.getText(); startBtn.setEnabled(
true); stopBtn.setEnabled(
true); }
else { javax.swing.JOptionPane.showMessageDialog(
null,
"portbeinputtedisillegal"); }}});headPanle.add(portLbl);headPanle.add(portTxt);headPanle.add(portSetBtn);getContentPane().add(headPanle,BorderLayout.NORTH); startBtn=
newJButton(
"Start"); stopBtn=
newJButton(
"Stop"); startBtn.setEnabled(
false); stopBtn.setEnabled(
false); mainPanle=
newJPanel(
newFlowLayout(FlowLayout.CENTER)); startBtn.addActionListener(
newStartClickListener()); stopBtn.addActionListener(
newActionListener() {
publicvoidactionPerformed(ActionEvente) { started=
false; clientList.clear();
try {
if(ss!=
null) {ss.close();}}
catch(IOExceptione1) {e1.printStackTrace();}}});mainPanle.add(startBtn);mainPanle.add(stopBtn);getContentPane().add(mainPanle,BorderLayout.CENTER); addWindowListener(
newWindowAdapter() {
publicvoidwindowClosing(WindowEvente) { started=
false; clientList.clear();
try {
if(ss!=
null) {ss.close();}}
catch(IOExceptione1) {e1.printStackTrace();}System.exit(0);}});
this.setSize(300,300); setLocation(100,100);pack(); setVisible(
true); }
privatevoidstart() {
try { ss=
newServerSocket(Integer.parseInt(port)); started=
true; }
catch(BindExceptionbe) { javax.swing.JOptionPane.showMessageDialog(
null,
"portisuseingbyothers"); }
catch(IOExceptione) { javax.swing.JOptionPane.showMessageDialog(
null,
"connectserverfail"); }
try {
while(started) {Sockets=ss.accept(); ClientImplcr=
newClientImpl(s);
newThread(cr).start(); clientList.add(cr); System.
out.println(
"SystemInfo:"+s.getInetAddress()+
"connectsuccessfully"); }}
catch(IOExceptione) { System.
out.println(
"Clientclosed!"); }}
classClientImplimplementsRunnable {
privateSockets;
privateDataInputStreamdis=
null;
privateDataOutputStreamdos=
null; booleanbConnect=
false;
publicClientImpl(Sockets) {
this.s=s;
try { dis=
newDataInputStream(s.getInputStream()); dos=
newDataOutputStream(s.getOutputStream()); bConnect=
true; }
catch(IOExceptione) {e.printStackTrace();}}
privatevoidsend(Stringstr) {
try {dos.writeUTF(str);}
catch(IOExceptione) {e.printStackTrace();}}
publicvoidrun() { ClientImplcr=
null;
try {
while(bConnect) {Stringstr=dis.readUTF(); System.
out.println(str);
for(
inti=0;i<clientList.size();i++) { cr=(ClientImpl)clientList.
get(i); cr.send(str);}}}
catch(Exceptione) {clientList.remove(cr); System.
out.println(s.getInetAddress()+
"hasleaved"); }
finally {
try {
if(dis!=
null) dis.close();
if(dos!=
null) dos.close();
if(s!=
null) {s.close(); s=
null; }}
catch(IOExceptionio) {io.printStackTrace();}}}}
classStartClickListenerimplementsRunnable,ActionListener {
publicvoidactionPerformed(ActionEvente) {
newThread(
this).start(); }
publicvoidrun() {start();}}}
客户端程序:
packagecom.test.talk;importjava.awt.BorderLayout;importjava.awt.FlowLayout; importjava.awt.
event.ActionEvent; importjava.awt.
event.ActionListener; importjava.awt.
event.WindowAdapter; importjava.awt.
event.WindowEvent; importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.Socket;importjava.net.UnknownHostException;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.JTextArea;importjavax.swing.JTextField;
publicclassClient {
publicstaticvoidmain(String[]args) { ClientFrameframe=
newClientFrame(); }}
classClientFrameextendsJFrame {
privateJPanelmainPanel;
privateJPanelheadPanel;
privateJPanelfootPanel;
privateJTextAreashowArea;
privateJTextFieldinputTxt;
privateJLabelportLbl;
privateJLabelipLbl;
privateJLabelnameLbl;
privateJTextFieldportTxt;
privateJTextFieldipTxt;
privateJTextFieldnameTxt;
privateJButtonsubmitBtn;
privateJButtonnameBtn;
privateJButtonloginBtn;
privateSocketclientSocket=
null;
privateDataOutputStreamdos=
null;
privateDataInputStreamdis=
null;
privatebooleanbConnect=
false;
privateStringname=
"";
publicClientFrame() {init();}
privatevoidinit() { mainPanel=
newJPanel(); showArea=
newJTextArea(15,80); showArea.setEditable(
false); mainPanel.add(showArea);getContentPane().add(mainPanel,BorderLayout.CENTER); headPanel=
newJPanel(
newFlowLayout(FlowLayout.LEFT)); portLbl=
newJLabel(
"PORT"); portTxt=
newJTextField(7); ipLbl=
newJLabel(
"IP"); ipTxt=
newJTextField(25); nameLbl=
newJLabel(
"name"); nameTxt=
newJTextField(15); nameBtn=
newJButton(
"OK"); loginBtn=
newJButton(
"login"); nameBtn.addActionListener(
newActionListener() {
publicvoidactionPerformed(ActionEvente) {Stringtmp=nameTxt.getText();
if(tmp!=
null||!tmp.equals(
"")) {
intid=javax.swing.JOptionPane.showConfirmDialog(
null,
"yesorno",
"chooseyes", javax.swing.JOptionPane.OK_OPTION);
if(id==0) {name=nameTxt.getText(); loginBtn.setEnabled(
true); nameBtn.setEnabled(
false); }}}});headPanel.add(portLbl);headPanel.add(portTxt);headPanel.add(ipLbl);headPanel.add(ipTxt);headPanel.add(loginBtn);headPanel.add(nameLbl);headPanel.add(nameTxt);headPanel.add(nameBtn); loginBtn.setEnabled(
false); loginBtn.addActionListener(
newButtonClickAction()); getContentPane().add(headPanel,BorderLayout.NORTH); footPanel=
newJPanel(
newFlowLayout(FlowLayout.LEFT)); inputTxt=
newJTextField(70); submitBtn=
newJButton(
"submit"); footPanel.add(inputTxt);footPanel.add(submitBtn); submitBtn.addActionListener(
newButtonClickAction()); submitBtn.setEnabled(
false); getContentPane().add(footPanel,BorderLayout.SOUTH); addWindowListener(
newWindowAdapter() {
publicvoidwindowClosing(WindowEvente) {disConnect();System.exit(0);}});
this.setSize(300,300); setLocation(100,100);pack(); setVisible(
true); }
classButtonClickActionimplementsActionListener {
publicvoidactionPerformed(ActionEvente) {
if(
"submit".equals(e.getActionCommand())) {Stringstr=inputTxt.getText().trim(); inputTxt.setText(
""); sendToServer(str);}
elseif(
"login".equals(e.getActionCommand())) {connect();}}}
classEnterClickActionimplementsActionListener {
publicvoidactionPerformed(ActionEvente) {Stringstr=inputTxt.getText().trim(); inputTxt.setText(
""); sendToServer(str);}}
privatevoidsendToServer(Stringstr) {
try { dos.writeUTF(name+
":"+str); dos.flush();}
catch(IOExceptione) {e.printStackTrace();}}
privatevoiddisConnect() {
try { bConnect=
false; }
catch(Exceptione) {e.printStackTrace();}}
privateclassReceiveimplementsRunnable {
publicvoidrun() {
try {
while(bConnect) {Stringstr=dis.readUTF(); showArea.setText(showArea.getText()+str+
'/n'); }}
catch(IOExceptione) { javax.swing.JOptionPane.showMessageDialog(
null,
"connectservererror"); }}}
privatevoidconnect() {
try {
if(ipTxt.getText().matches(
"//d{1,3}.//d{1,3}.//d{1,3}.//d{1,3}")&&portTxt.getText().matches(
"//d+")) { clientSocket=
newSocket(ipTxt.getText(),Integer.parseInt(portTxt.getText())); dos=
newDataOutputStream(clientSocket.getOutputStream()); dis=
newDataInputStream(clientSocket.getInputStream()); bConnect=
true;
newThread(
newReceive()).start(); System.
out.println(
"Iamcoming"); javax.swing.JOptionPane.showMessageDialog(
null,
"connectserversuccess"); submitBtn.setEnabled(
true); inputTxt.addActionListener(
newEnterClickAction()); }
else { javax.swing.JOptionPane.showMessageDialog(
null,
"portoripbeinputtedisillegal"); }}
catch(UnknownHostExceptionuhe) { javax.swing.JOptionPane.showMessageDialog(
null,
"connectservererror"); }
catch(IOExceptione) { javax.swing.JOptionPane.showMessageDialog(
null,
"connectservererror"); }}}
使用说明:
1.先运行服务器端程序,设定好端口号
2.点击Start按钮,运行服务器
3.运行客户端程序
4.设定好昵称
5.设定与服务器端匹配的端口号和服务器的ip地址
6.点击Login按钮,登录到聊天系统
7.可以聊天了。
相关资源:JAVA课件(高级程序设计,socket编程,图形界面,多线程)