Socket简单实例

举报
小傅哥 发表于 2021/04/23 00:47:53 2021/04/23
【摘要】 Server端 import java.net.*; import java.util.*; import java.io.*; import java.awt.*; import java.awt.event.*; public class ChatServer extends Frame {  TextArea ta = new TextArea(); &n...

Server端

import java.net.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class ChatServer extends Frame
{
 TextArea ta = new TextArea();
 public void launchFrame()
 {
  add(ta, BorderLayout.CENTER);
  setBounds(0,0,200,300); 
  this.addWindowListener(
   new WindowAdapter()
   {
    public void windowClosing(WindowEvent e)
    {
     System.exit(0);
    }
   }
   );
  setVisible(true);
 }
 
 ServerSocket server = null;
 Collection cClient = new ArrayList();
 
 public ChatServer(int port) throws Exception
 {
  server = new ServerSocket(port);
  launchFrame();
 }
 
 public void startServer() throws Exception
 {
  while(true)
  {
   Socket s = server.accept();
   cClient.add( new ClientConn(s) );
   ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
   ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
  }
 }
 
 class ClientConn implements Runnable
 {
  Socket s = null;
  public ClientConn(Socket s)
  {
   this.s = s;
   (new Thread(this)).start();
  }
  
  public void send(String str) throws IOException
  {
   DataOutputStream dos = new DataOutputStream(s.getOutputStream());
   dos.writeUTF(str);
  }
  
  public void dispose()
  {
   try {
    if (s != null) s.close();
    cClient.remove(this);
    ta.append("A client out! \n");
    ta.append("CLIENT-COUNT: " + cClient.size() + "\n\n");
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
  
  public void run()
  {
   try {
    
    DataInputStream dis = new DataInputStream(s.getInputStream());
    String str = dis.readUTF();
    while(str != null && str.length() !=0)
    {
     System.out.println(str);
     for(Iterator it = cClient.iterator(); it.hasNext(); )
     {
      ClientConn cc = (ClientConn)it.next();
      if(this != cc)
      {
       cc.send(str);
      }
     }
     str = dis.readUTF();
     //send(str);
    }
    this.dispose();
   }
   catch (Exception e)
   {
    System.out.println("client quit");
    this.dispose();
   }
   
  }
 }
 
 public static void main(String[] args) throws Exception
 {
  ChatServer cs = new ChatServer(8888);
  cs.startServer();
 }
}

Client端

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient extends Frame
{
 TextArea ta = new TextArea();
 TextField tf = new TextField();
 public void launchFrame() throws Exception
 {
  this.add(ta, BorderLayout.CENTER);
  this.add(tf, BorderLayout.SOUTH);
  tf.addActionListener(
   new ActionListener()
   {
    public void actionPerformed(ActionEvent ae)
    {
     try {
      String sSend = tf.getText();
      if(sSend.trim().length() == 0) return;
      ChatClient.this.send(sSend);
      tf.setText("");
      ta.append(sSend + "\n");
     }
     catch (Exception e) { e.printStackTrace(); }
    }
   }
   );
  
  this.addWindowListener(
   new WindowAdapter()
   {
    public void windowClosing(WindowEvent e)
    {
     System.exit(0);
    }
   }
   );
  setBounds(300,300,300,400);
  setVisible(true);
  tf.requestFocus();
 }
 
 Socket s = null;
 
 public ChatClient() throws Exception
 {
  s = new Socket("127.0.0.1", 8888);
  launchFrame();
  (new Thread(new ReceiveThread())).start();
 }
 
 public void send(String str) throws Exception
 {
  DataOutputStream dos = new DataOutputStream(s.getOutputStream());
  dos.writeUTF(str);
 }
 
 public void disconnect() throws Exception
 {
  s.close();
 }
 
 public static void main(String[] args) throws Exception
 {
  BufferedReader br = new BufferedReader (
        new InputStreamReader(System.in));
  ChatClient cc = new ChatClient();
  String str = br.readLine();
  while(str != null && str.length() != 0)
  {
   cc.send(str);
   str = br.readLine();
  }
  cc.disconnect();
 }
 
 class ReceiveThread implements Runnable
 {
  public void run()
  {
   if(s == null) return;
   try {
    DataInputStream dis = new DataInputStream(s.getInputStream());
    String str = dis.readUTF();
    while (str != null && str.length() != 0)
    {
     //System.out.println(str);
     ChatClient.this.ta.append(str + "\n");
     str = dis.readUTF();
    }
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
   
  }
 }
}

 

文章来源: bugstack.blog.csdn.net,作者:Yao__Shun__Yu,版权归原作者所有,如需转载,请联系作者。

原文链接:bugstack.blog.csdn.net/article/details/7790843

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。