首页>代码>java socket开发最简易的聊天室源码分享>/JAVA聊天室/SocketServerExample.java
//服务器端程序
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class SocketServerExample extends Frame implements ActionListener
{ Label label=new Label("输入聊天信息");
  TextField tf= new TextField(20);
  TextArea ta=new TextArea( );
      Panel panel=new Panel( );//创建面板对象
  ServerSocket server;
  Socket Client;
  InputStream DataIn;
  OutputStream DataOut;
  public SocketServerExample( )
  { super("这里是服务器");
    setSize(300,180);
    panel.add(label);//在面板上添加标签
    panel.add(tf);//在面板上添加文本框
    tf.addActionListener(this);//注册
    add("North",panel);//在窗体上添加面板
    add("Center",ta);//在窗体上添加文本区
    addWindowListener(new WindowAdapter( )
    { public void windowClosing(WindowEvent e)
    { System.exit(0);}});
    show( );
    try
    	{ server =new ServerSocket(5000);
    	   Client=server.accept( );
    	   ta.append("已经和客户机连接:"+Client.getInetAddress( ).getHostName( )+"\n\n");
    	   DataIn=Client.getInputStream( );
    	   DataOut=Client.getOutputStream( );	
    }
    catch(IOException ioe){ }
    while(true)
    {
    	try{
    		byte buff[ ]=new byte[512];//缓冲数组
    		DataIn.read(buff);
    		String str=new String(buff);//接受客户端发送的数据包
    		ta.append("客户机说:"+str+"\n");
    	}
    	catch(IOException ioe){ }
    }
    }
    public static void main(String args[ ])
    {
    	new SocketServerExample( );
    }
    public void actionPerformed(ActionEvent e)//事件处理程序
    {
    	try 
    		{
    		String str=new String(tf.getText());
    		byte buf[ ]=str.getBytes( );
    		tf.setText(" ");
    		DataOut.write(buf);
    		ta.append("服务器说:"+str+"\n\n");
    	}
    		catch(IOException ioe){ }
    }
    }
  
最近下载更多
zeng1206  LV7 2023年12月28日
bearloadprogress  LV7 2022年5月12日
王子慷  LV1 2022年2月24日
tangjj7260  LV18 2021年12月10日
hemayah  LV2 2021年10月5日
zk1259  LV6 2021年8月13日
美滋滋  LV1 2021年7月5日
wahaha19205019  LV1 2021年6月30日
dragsivan  LV1 2021年6月25日
年轻的人  LV1 2021年6月12日
最近浏览更多
爱情戴罪的羔羊  LV7 3月1日
chuxue11  LV2 2024年11月18日
124324343  LV1 2024年6月27日
qwertasdfgkwuejwjwjw  LV1 2024年6月27日
周鸣郝  LV2 2024年5月26日
微信网友_7004855557083136  LV1 2024年5月22日
xiaokang1  LV10 2024年3月29日
zeng1206  LV7 2023年12月28日
1234567p  LV1 2023年12月4日
EFWAGGFAWGR 2023年10月19日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友