Posted on 2006-11-26 20:43
黑夜ちつ独行者 阅读(1147)
评论(0) 编辑 收藏
1)建立一个服务器ServerSocket,并同时定义好ServerSocket的监听端口;
2)ServerSocket 调用accept()方法,使之处于阻塞。
3)创建一个客户机Socket,并设置好服务器的IP和端口。
4)客户机发出连接请求,建立连接。
5)分别取得服务器和客户端ServerSocket 和Socket的InputStream和OutputStream.
6) 利用Socket和ServerSocket进行数据通信。
服务器:
import java.net.*;
import java.io.*;
public class MypwServer {
public MypwServer() {
super();
// TODO Auto-generated constructor stub
}
public void Activate() throws Exception{
ServerSocket ss = new ServerSocket(5678);
Socket soc = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
PrintWriter pw = new PrintWriter(soc.getOutputStream());
while(true){
String str = br.readLine();
pw.println(str);
//pw.flush();
// if(str.equals("end")){
// break;
// }
// System.out.println(str);
}
}
public static void main(String[] args){
MypwServer mys = new MypwServer();
try {
mys.Activate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Client extends JFrame implements ActionListener
{
static String str;
static String sy;
static PrintStream p;
JButton btn,btn1;
JLabel ble;
static JTextArea tex = new JTextArea();
static JTextArea tex1 = new JTextArea();
public Client()
{
this.setTitle("聊天室");
this.setSize(500,420);
this.setLocation(230,60);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLayout(null);
Container con = this.getContentPane();
btn = new JButton("发送");
btn1 = new JButton("关闭");
btn.addActionListener(this);
btn1.addActionListener(this);
btn.setBounds(20,360,60,20);
btn1.setBounds(120,360,60,20);
tex.setBounds(0,0,250,150);
tex1.setBounds(0,180,250,160);
con.add(btn);
con.add(btn1);
con.add(tex);
con.add(tex1);
this.setVisible(true);
}
客户机:
public static void main(String[] args) throws Exception
{
new Client();
Socket so = new Socket("localhost",5678);
BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream()));
p = new PrintStream(so.getOutputStream());
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
str = tex1.getText();
if (str.equals(null))
break;
}
so.close();
}
public void actionPerformed(ActionEvent a)
{
Object obj = a.getSource();
if(obj == btn)
{
p.println(str);
tex.append(str + "\n");
tex1.setText("");
}
if(obj == btn1)
{
System.exit(0);
}
}
}