欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java基于socket实现的客户端和服务端通信功能完整实例

程序员文章站 2023-12-18 22:01:46
本文实例讲述了java基于socket实现的客户端和服务端通信功能。分享给大家供大家参考,具体如下: 以下代码参考马士兵的聊天项目,先运行chatserver.java实...

本文实例讲述了java基于socket实现的客户端和服务端通信功能。分享给大家供大家参考,具体如下:

以下代码参考马士兵的聊天项目,先运行chatserver.java实现端口监听,然后再运行chatclient.java

客户端实例

chatclient.java

package socketdemo;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class chatclient extends frame {
  socket s = null;
  dataoutputstream dos = null;
  datainputstream dis = null;
  private boolean bconnected = false;
  textfield tftxt = new textfield();
  textarea tacontent = new textarea();
  thread trecv = new thread(new recvthread());
  public static void main(string[] args) {
    new chatclient().launchframe();
  }
  public void launchframe() {
    setlocation(400, 300);
    this.setsize(300, 300);
    add(tftxt, borderlayout.south);
    add(tacontent, borderlayout.north);
    pack();
    this.addwindowlistener(new windowadapter() {
      @override
      public void windowclosing(windowevent arg0) {
        disconnect();
        system.exit(0);
      }
    });
    tftxt.addactionlistener(new tflistener());
    setvisible(true);
    connect();
    trecv.start();
  }
  public void connect() {
    try {
      s = new socket("localhost", 8888);
      dos = new dataoutputstream(s.getoutputstream());
      dis = new datainputstream(s.getinputstream());
      system.out.println("connected!");
      bconnected = true;
    } catch (unknownhostexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }
  public void disconnect() {
    try {
      dos.close();
      dis.close();
      s.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
    /*
     * try { bconnected = false; trecv.join(); } catch(interruptedexception
     * e) { e.printstacktrace(); } finally { try { dos.close(); dis.close();
     * s.close(); } catch (ioexception e) { e.printstacktrace(); } }
     */
  }
  private class tflistener implements actionlistener {
    public void actionperformed(actionevent e) {
      string str = tftxt.gettext().trim();
      // tacontent.settext(str);
      tftxt.settext("");
      try {
        // system.out.println(s);
        dos.writeutf(str);
        dos.flush();
        // dos.close();
      } catch (ioexception e1) {
        e1.printstacktrace();
      }
    }
  }
  private class recvthread implements runnable {
    public void run() {
      try {
        while (bconnected) {
          string str = dis.readutf();
          // system.out.println(str);
          tacontent.settext(tacontent.gettext() + str + '\n');
        }
      } catch (socketexception e) {
        system.out.println("退出了,bye!");
      } catch (eofexception e) {
        system.out.println("推出了,bye - bye!");
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
  }
}

socket服务端代码

chatserver.java

package socketdemo;
import java.io.*;
import java.net.*;
import java.util.*;
public class chatserver {
  boolean started = false;
  serversocket ss = null;
  list<client> clients = new arraylist<client>();
  public static void main(string[] args) {
    new chatserver().start();
  }
  public void start() {
    try {
      ss = new serversocket(8888);
      started = true;
    } catch (bindexception e) {
      system.out.println("端口使用中....");
      system.out.println("请关掉相关程序并重新运行服务器!");
      system.exit(0);
    } catch (ioexception e) {
      e.printstacktrace();
    }
    try {
      while (started) {
        socket s = ss.accept();
        client c = new client(s);
        system.out.println("a client connected!");
        new thread(c).start();
        clients.add(c);
        // dis.close();
      }
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      try {
        ss.close();
      } catch (ioexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
      }
    }
  }
  class client implements runnable {
    private socket s;
    private datainputstream dis = null;
    private dataoutputstream dos = null;
    private boolean bconnected = false;
    public client(socket s) {
      this.s = s;
      try {
        dis = new datainputstream(s.getinputstream());
        dos = new dataoutputstream(s.getoutputstream());
        bconnected = true;
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    public void send(string str) {
      try {
        dos.writeutf(str);
      } catch (ioexception e) {
        clients.remove(this);
        system.out.println("对方退出了!我从list里面去掉了!");
        // e.printstacktrace();
      }
    }
    public void run() {
      try {
        while (bconnected) {
          string str = dis.readutf();
          system.out.println(str);
          for (int i = 0; i < clients.size(); i++) {
            client c = clients.get(i);
            c.send(str);
            // system.out.println(" a string send !");
          }
          /*
           * for(iterator<client> it = clients.iterator();
           * it.hasnext(); ) { client c = it.next(); c.send(str); }
           */
          /*
           * iterator<client> it = clients.iterator();
           * while(it.hasnext()) { client c = it.next(); c.send(str);
           * }
           */
        }
      } catch (eofexception e) {
        system.out.println("client closed!");
      } catch (ioexception e) {
        e.printstacktrace();
      } finally {
        try {
          if (dis != null)
            dis.close();
          if (dos != null)
            dos.close();
          if (s != null) {
            s.close();
            // s = null;
          }
        } catch (ioexception e1) {
          e1.printstacktrace();
        }
      }
    }
  }
}

本机测试运行结果:

Java基于socket实现的客户端和服务端通信功能完整实例

关闭客户端窗口后,提示信息如下:

Java基于socket实现的客户端和服务端通信功能完整实例

更多关于java相关内容感兴趣的读者可查看本站专题:《java socket编程技巧总结》、《java文件与目录操作技巧汇总》、《java数据结构与算法教程》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

上一篇:

下一篇: