当前位置:文档之家› 服务器和客户端通信

服务器和客户端通信

实验六基于TCP/IP的网络编程1 实验目的MFC提供的关于网络应用的类CSocket是一个比较高级的封装,使用它编制出属于自己的网络应用程序,可以编一个属于自己的网络通讯软件。

通过这个实验,同学们也可以增进对于TCP/IP协议的理解。

2 实验内容基于TCP/IP的通信基本上都是利用SOCKET套接字进行数据通讯,程序一般分为服务器端和用户端两部分。

设计思路(VC6.0下):第一部分服务器端一、创建服务器套接字(create)。

二、服务器套接字进行信息绑定(bind),并开始监听连接(listen)。

三、接受来自用户端的连接请求(accept)。

四、开始数据传输(send/receive)。

五、关闭套接字(closesocket)。

第二部分客户端一、创建客户套接字(create)。

二、与远程服务器进行连接(connect),如被接受则创建接收进程。

三、开始数据传输(send/receive)。

四、关闭套接字(closesocket)。

CSocket的编程步骤:(注意我们一定要在创建MFC程序第二步的时候选上Windows Socket 选项,其中ServerSocket是服务器端用到的,ClientSocket是客户端用的。

)(1)构造CSocket对象,如下例:CSocket ServerSocket;CSocket ClientSocket;(2)CSocket对象的Create函数用来创建Windows Socket,Create()函数会自行调用Bind()函数将此Socket绑定到指定的地址上面。

如下例:ServerSocket.Create(823); //服务器端需要指定一个端口号,我们用823。

ClientSocket.Create(); //客户端不用指定端口号。

(3)现在已经创建完基本的Socket对象了,现在我们来启动它,对于服务器端,我们需要这个Socket不停的监听是否有来自于网络上的连接请求,如下例:ServerSocket.Listen(5);//参数5是表示我们的待处理Socket队列中最多能有几个Socket。

(4)对于客户端我们就要实行连接了,具体实现如下例:ClientSocket.Connect(CString SerAddress,Unsinged int SerPort);//其中SerAddress是服务器的IP地址,SerPort是端口号。

(5)服务器是怎么来接受这份连接的呢?它会进一步调用Accept(ReceiveSocket)来接收它,而此时服务器端还须建立一个新的CSocket对象,用它来和客户端进行交流。

如下例:CSocket ReceiveSocket;ServerSocket.Accept(ReceiveSocket);(6)如果想在两个程序之间接收或发送信息,MFC也提供了相应的函数。

(7)代码package test.socket3;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.DataOutputStream;import java.io.IOException;import javax.swing.JTextArea;import javax.swing.JTextField;public class ClientListener implements ActionListener { private MyClient cf;public ClientListener(MyClient cf) {this.cf = cf;}@Overridepublic void actionPerformed(ActionEvent e) {JTextField tf2 = cf.getTf2();JTextArea ta =cf.getTa();DataOutputStream dos = cf.getDos();String info = tf2.getText();try {dos.writeUTF(info);ta.append("客户端:"+info+"\n");} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}tf2.setText("");tf2.requestFocus();if (info.equals("bye")) {cf.close();}}}package test.socket3;import java.io.DataInputStream;import java.io.IOException;import javax.swing.JTextArea;public class ClientReader extends Thread{private MyClient cf;public ClientReader(MyClient cf) {this.cf = cf;}@Overridepublic void run() {DataInputStream dis =cf.getDis();JTextArea ta =cf.getTa();String info;while(cf.isFlag()){try {info=dis.readUTF();ta.append("服务器:"+info+"\n");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}package test.socket3;import java.awt.Color;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import .Socket;import .UnknownHostException;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class MyClient{private DataInputStream dis;private DataOutputStream dos; private Socket s;private String ip;private JPanel panel;private JLabel lbl1;private JLabel lbl2;private JButton btn_Send;private JButton btn_Link;private JTextArea ta;private JTextField tf1;private JTextField tf2;private JFrame f;private boolean flag=true;//封装的get set 方法public JTextArea getTa() {return ta;}public void setTa(JTextArea ta) {this.ta = ta;}public JTextField getTf1() {return tf1;}public void setTf1(JTextField tf1) {this.tf1 = tf1;}public JTextField getTf2() {return tf2;}public void setTf2(JTextField tf2) {this.tf2 = tf2;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public DataInputStream getDis() {return dis;}public void setDis(DataInputStream dis) {this.dis = dis;}public DataOutputStream getDos() {return dos;}public void setDos(DataOutputStream dos) {this.dos = dos;}public boolean isFlag() {return flag;}/*** 客户端窗体方法*/public void creatClientFrame(){f=new JFrame();f.setTitle("客户端");f.setSize(800,800);f.setLocation(200, 100);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//初始化panel =new JPanel();lbl1=new JLabel("IP:");lbl2=new JLabel("消息栏");btn_Send=new JButton("发送");btn_Link=new JButton("连接");ta=new JTextArea();tf1=new JTextField();tf2=new JTextField();//设置字体和颜色Font font1 =new Font("新宋体", Font.BOLD, 20);Font font2 =new Font("新宋体", Font.BOLD, 30);lbl1.setFont(font1);lbl2.setFont(font2);tf1.setFont(font1);tf2.setFont(font1);ta.setFont(font1);lbl2.setForeground(Color.blue);btn_Send.setFont(font1);btn_Link.setFont(font1);//事件//连接btn_Link.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubip=tf1.getText();try {s=new Socket(ip,8888);dis=new DataInputStream(s.getInputStream());dos=new DataOutputStream(s.getOutputStream());ta.append("成功连接到服务器!\n");} catch (UnknownHostException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}});ClientListener cl=new ClientListener(this);//发送btn_Send.addActionListener(cl);tf2.addActionListener(cl);//设置样式panel.setLayout(null);lbl1.setBounds(10, 10, 50,50);tf1.setBounds(60, 10, 500, 50);btn_Link.setBounds(600, 10, 150, 50);lbl2.setBounds(0,60, 100, 50);ta.setBounds(0, 110,700, 500);tf2.setBounds(0, 610, 550, 100);btn_Send.setBounds(550,610,150, 100);ta.setEditable(false);//设置文本域的可编辑型//添加panel.add(lbl1);panel.add(tf1);panel.add(btn_Link);panel.add(lbl2);panel.add(ta);panel.add(tf2);panel.add(btn_Send);f.add(panel);f.setVisible(true);tf1.requestFocus();}/*** 停止接受线程*/public void stop(){flag=false;}/*** 关闭线程的方法*/public void close(){try {dos.writeUTF("bye");ta.append("客户端将在5秒后退出");this.stop();try {Thread.sleep(5000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}dis.close();dos.close();s.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.exit(0);}/*** 创建接受消息,并启动线程*/public void creatThread(){ClientReader cr=new ClientReader(this);cr.start();}/*** 连接方法*///public void connect(){//try {//s=new Socket("127.0.0.1",8888);//dis=new DataInputStream(s.getInputStream());//dos=new DataOutputStream(s.getOutputStream()); //} catch (UnknownHostException e) {//// TODO Auto-generated catch block// e.printStackTrace();//} catch (IOException e) {//// TODO Auto-generated catch block// e.printStackTrace();//}//}/*** 主方法* @param args*/public static void main(String[] args) {MyClient mc=new MyClient();mc.creatClientFrame();//mc.connect();//mc.creatThread();while(true){if(mc.getDis()!=null&&mc.getDos()!=null){mc.creatThread();break;}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}package test.socket3;import java.awt.Color;import java.awt.Font;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import .ServerSocket;import .Socket;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class MyServer {private DataOutputStream dos;//输出流private DataInputStream dis;private ServerSocket ss;private JPanel panel;private JButton btn_Send;private JLabel lbl;private JTextArea ta;//文本域private JTextField tf;//文本框private JFrame f;//窗体private boolean flag=true;//封装get,set方法public JTextField getTf() {return tf;}public void setTf(JTextField tf) {this.tf = tf;}public void setTa(JTextArea ta) {this.ta = ta;}public JTextArea getTa() {return ta;}public DataOutputStream getDos() {return dos;}public void setDos(DataOutputStream dos) { this.dos = dos;}public DataInputStream getDis() {return dis;}public void setDis(DataInputStream dis) {this.dis = dis;}public boolean isFlag() {return flag;}public void creatFrame(){f=new JFrame();f.setTitle("服务器");f.setSize(800,800);f.setLocation(200, 100);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//初始化panel=new JPanel();btn_Send=new JButton("发送");lbl=new JLabel("消息栏");ta=new JTextArea();tf=new JTextField();//字体样式和颜色Font font1 =new Font("新宋体",Font.BOLD, 30);Font font2 =new Font("新宋体",Font.BOLD, 20);lbl.setFont(font1);ta.setFont(font2);tf.setFont(font2);btn_Send.setFont(font1);lbl.setForeground(Color.blue);//事件发送ServerListener sl=new ServerListener(this);btn_Send.addActionListener(sl);//文本框事件监听器tf.addActionListener(sl);//设置样式panel.setLayout(null);lbl.setBounds(0, 0, 100, 50);ta.setBounds(0, 50, 700,500);tf.setBounds(0, 550,550, 100);btn_Send.setBounds(550, 550, 150, 100);ta.setEditable(false);//设置文本域的可编辑型//添加panel.add(lbl);panel.add(btn_Send);panel.add(ta);panel.add(tf);f.add(panel);f.setVisible(true);tf.requestFocus();}/*** 停止接受线程*/public void stop(){this.flag=false;}/*** 关闭线程*/public void close(){try {dos.writeUTF("bye");ta.append("服务器将在5秒后退出!");this.stop();try {Thread.sleep(5000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}dis.close();dos.close();ss.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.exit(0);}/*** 接受消息*/public void creatThread(){ServerReader sr=new ServerReader(this);sr.start();}/*** 连接方法*/public void connect(){try {ss=new ServerSocket(8888);Socket s=ss.accept();//连接服务器成功ta.append("客户端连接到服务器!\n");dis=new DataInputStream(s.getInputStream());dos=new DataOutputStream(s.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 主方法* @param args*/public static void main(String[] args) {MyServer ms=new MyServer();ms.creatFrame();ms.connect();ms.creatThread();}}package test.socket3;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.DataOutputStream;import java.io.IOException;import javax.swing.JTextArea;import javax.swing.JTextField;public class ServerListener implements ActionListener { private MyServer ms;public ServerListener(MyServer ms) {this.ms = ms;}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubJTextField tf = ms.getTf();JTextArea ta =ms.getTa();DataOutputStream dos = ms.getDos();String info = tf.getText();try {dos.writeUTF(info);ta.append("服务器:"+info+"\n");} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}tf.setText("");tf.requestFocus();if (info.equals("bye")) {ms.close();}}}package test.socket3;import java.io.DataInputStream;import java.io.IOException;import javax.swing.JTextArea;public class ServerReader extends Thread {private MyServer ms;public ServerReader(MyServer ms) {this.ms = ms;}@Overridepublic void run() {DataInputStream dis=ms.getDis();JTextArea ta=ms.getTa();String info;while(ms.isFlag()){try {info=dis.readUTF();ta.append("客户端:"+info+"\n");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}。

相关主题