求用socket收发信息的applet

joycao 2002-07-10 05:05:51
就是想学习一下别人的原码
...全文
55 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qxjavajava 2002-07-10
  • 打赏
  • 举报
回复
import java.net.*;
import java.io.*;
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class ChatRoom extends Applet implements Runnable,ActionListener
{ Button button;TextField text1;TextArea text2;
Socket socket;
DataInputStream in;
DataOutputStream out;
Thread thread;
public void init()
{setBackground(new Color(113,163,139));
setLayout(new BorderLayout());
button=new Button("send");text1=new TextField(12);
text2=new TextArea();
Panel p=new Panel();p.add(text1);p.add(button);
add("Center",text2);add("South",p);
button.addActionListener(this);
}
public void start()
{ try
{socket = new Socket(this.getCodeBase().getHost(), 4331);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch (IOException e){}
if (thread == null)
{thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
}
public void run()
{String s1=null;
while(true)
{ try{s1=in.readUTF();// 通过使用in读取服务器放入“线路”里的信息
}
catch (IOException e) {}
if(s1.equals("bye"))
{try{socket.close();break;}
catch (IOException e) {}
}
text2.append(s1+"\n");
}
}
public void actionPerformed(ActionEvent e)
{if (e.getSource()==button)
{ String s=text1.getText();
if(s!=null)
{ try{out.writeUTF(s);}
catch(IOException e1){}
}
else
{ try{out.writeUTF("请说话");}
catch(IOException e1){}
}
}
}
}
2)服务器端
import java.io.*;import java.net.*;
import java.util.*;
public class ServerTwo
{
public static void main(String args[])
{ ServerSocket server=null;Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);}
catch(IOException e1) {System.out.println("正在监听"+"ERRO:"+e1);}
try{ you=server.accept();}
catch (IOException e)
{System.out.println("正在等待客户");}
if(you!=null)
{new Server_thread(you).start(); }
else {continue;}//继续等待客户的呼叫
}
}
}
class Server_thread extends Thread
{ Socket socket;
DataOutputStream out=null;DataInputStream in=null;
String s=null;
Server_thread(Socket t)
{ socket=t;
try {in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ try{s=in.readUTF();// 通过使用in读取客户放入“线路”里的信息
}
catch (IOException e) {System.out.println("ERRO:"+e);}
try {if(s.equals("bye"))
{out.writeUTF(s);socket.close() ; }//客户以离开
else{ try{out.writeUTF("我是服务器你对我说:"+s);}
//通过 out向“线路”写入信息
catch (IOException e) {}
}
}
catch (IOException e) {}
}
}
}
olvest4000 2002-07-10
  • 打赏
  • 举报
回复
www.cn-java.com/socketr

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧