/*SocketServer.java*/importjava.awt.*;importjava.awt.event.*;publicclassSocketServerextendsFrameimplementsActionListener{Labellabel=newLabel("输入聊天信息,按回车发送!");...
/*SocketServer.java*/
import java.awt.*;
import java.awt.event.*;
public class SocketServer 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 SocketServer( )
{
super("服务器 ");
setSize(380,300);
panel.add(label);
panel.add(tf);
tf.addActionListener(this);
add("North",panel);
add("Center",ta);
ta.setBackground(Color.black);
ta.setForeground(Color.yellow);
addWindowListener(new WindowAdapter( )
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
show( );
try
{
server =new ServerSocket(5000);
while(true)
{
Client=server.accept( );
Thread thread=new Thread();
thread.start();
ta.append("已经和客户机连接:"+Client.getInetAddress( )+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 SocketServer( );
}
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");
}catch(IOException ioe){ }
}
}
可以再加分,谢谢!
上面是服务器程序,客户端就不发了,这是一个socket通信的聊天程序,在我源程序上改,大改小改都可以,
谢谢!
展开