服务端的程序:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class ChatroomServer extends Frame implements ActionListener //创建可视化窗口
{
Button btn=new Button("发送"); //创建按钮
TextArea serverMsg; //创建文本域
InputStream ins; //流对象
OutputStream outs;
Socket sock;
ServerSocket server;
public ChatroomServer(){ //初始化窗口
setTitle("Server Window");
setLayout(new BorderLayout());
serverMsg=new TextArea(10,50);
btn.addActionListener(this);
add("South",btn);
add("Center",serverMsg);
setResizable(false);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);}});
pack();
setVisible(true);
try //通过socket类中的方法实现端口的监听、接收客户端请求功能
{
server=new ServerSocket(9000);
sock=server.accept();
InetAddress ClientAddress=sock.getInetAddress();
serverMsg.append("已接收到客户机:"+ClientAddress.toString()+"\n");
ins=sock.getInputStream();
outs=sock.getOutputStream();
}
catch(IOException ioe)
{
}
while(true) //创建缓冲区用以接收客户端的流
{
try{
byte[] buf=new byte[256];
ins.read(buf);
String str=new String(buf);
serverMsg.append("客户机:"+str+"\n");
serverMsg.append("\n");
}
catch(IOException e)
{
}
}
}
public void actionPerformed(ActionEvent e) //定义窗口控件功能
{
try
{
String str=serverMsg.getText();
byte[ ] buf=str.getBytes();
serverMsg.setText("");
outs.write(buf);
}
catch(IOException ioe){}
}
public static void main(String[] args)
{
new ChatroomServer();
}
}
客户端的程序:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.*;
import java.io.*;
public class ChatroomClient extends Frame implements ActionListener
{
Socket client;
OutputStream os;
InputStream ins;
String s;
TextArea textArea;
Button Mybutton=new Button("发送");
public ChatroomClient()
{
setTitle("Client window");
setLayout(new BorderLayout());
Mybutton.addActionListener(this);
textArea=new TextArea(10,50);
add("South",Mybutton);
add("Center",textArea);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);}});
setResizable(false);
pack();
setVisible(true);
try
{
client=new Socket(InetAddress.getLocalHost(),9000);
textArea.append("已连接服务器"+client.getInetAddress().getHostName()+":\n");
ins=client.getInputStream();
os=client.getOutputStream();
}
catch(IOException e)
{
while(true)
{
try
{
byte[] buf=new byte[256];
ins.read(buf);
String str=new String(buf);
textArea.append("服务器"+str);
textArea.append("\n");
}
catch(IOException ioe)
{
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==Mybutton)
try
{
String str=textArea.getText();
byte[ ] buf=str.getBytes();
textArea.setText("");
os.write(buf);
}
catch(IOException ioe){}
}
public static void main(String[] args)
{
new ChatroomClient();
}
}
功能描述:图像化的窗口,实现客户端与服务器端的消息发送。
问题:socket类中的getinputstream()方法返回套接字的输入流,getoutputstream()方法返回套接字输出流,在客户端和服务器端都有实现,不知道问题出在哪里……?只能从客户端发消息,服务端可以接,但是反过来不行。
谢谢!
|