码迷,mamicode.com
首页 > 编程语言 > 详细

[Java] Tcp/udp 简单通信

时间:2014-07-16 17:23:23      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:tcp   java   udp   通信   图形   

本文转自  我自己的博客guozeyiblog.cn 欢迎来访

效果图:

bubuko.com,布布扣

        //UDP通信

    import java.awt.*;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.io.IOException;

    import java.net.*;

    import javax.swing.*;

    class send extends JFrame implements ActionListener{

    	private JTextArea Chat; //显示框

    	private JTextField Mes; //输入框

    	DatagramSocket soc;

    	public send(){ //构造函数

    		 try {

    			 soc = new DatagramSocket();

    		} catch (SocketException e) {

    			// TODO 自动生成的 catch 块

    			e.printStackTrace();

    		}

    		GUI("客户端");

    		while(true){

    			GetMsg();

    		}

    	}

    	

    	public static void main(String args[]){

    		new send();

    	}

    	

    	public void GUI(String str){ //图形化界面

    		this.setTitle(str);

    		Container container = this.getContentPane();

    		JButton send = new JButton("发送");

    		JLabel msg = new JLabel("消息内容");

    		Chat = new JTextArea();

    		Mes = new JTextField(20);

    		Chat.setEditable(false);

    		JScrollPane contain = new JScrollPane(); //滚动框

            contain.setViewportView(Chat);

            container.setLayout(new BorderLayout()); //设置布局方式

            container.add(contain,BorderLayout.CENTER);

            JPanel botton = new JPanel();

            Mes.addActionListener(this);

            send.addActionListener(this); //绑定监听

            botton.add(msg);

            botton.add(Mes);

            botton.add(send);

            container.add(botton,BorderLayout.SOUTH);

            this.show(true);

            this.setSize(600, 400);

    	}

    	//与Button绑定的方法

    	public void actionPerformed(ActionEvent e) {

    	  String str = Mes.getText();  //取得文本域的内容

    	  if(str.equals("")){

    		  Chat.append("提示:消息不可以为空!!!\n");

    	  }else{

    		  Chat.append("我说:"+str+"\n");

    		  //UDP发包

    		  SendMsg(str);

    	  }

    	  Mes.setText("");

    	}

    	

    	//发包

    	public void SendMsg(String str){

    		try {

    			DatagramPacket packet = new DatagramPacket(str.getBytes(),str.getBytes().length, 

    					InetAddress.getByName("127.0.0.1"),11190);		   

    		    soc.send(packet);

    		} catch (Exception e) {

    			// TODO 自动生成的 catch 块

    			e.printStackTrace();

    		}		

    	}

    	

    	//接收

    	public void GetMsg(){

    		byte data[]= new byte[1024];

    		DatagramPacket packet = new DatagramPacket(data,data.length);

    		try {

    		    //DatagramSocket soc = new DatagramSocket();		

    			soc.receive(packet);

    		} catch (IOException e) {

    			// TODO 自动生成的 catch 块

    			e.printStackTrace();

    		}

    		Chat.append("服务:"+new String(packet.getData(),0,packet.getData().length)+"\n");

    	}

    }

     
     

     
     

        //UDP通信

    import java.awt.*;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.io.IOException;

    import java.net.*;

    import javax.swing.*;

    class recevice extends JFrame implements ActionListener{

    	private JTextArea Chat; //显示框

    	private JTextField Mes; //输入框

    	DatagramSocket soc;

    	InetAddress adr;

    	int port;

    	public recevice(){ //构造函数

    		try {

    			soc = new DatagramSocket(11190);

    		} catch (SocketException e) {

    			// TODO 自动生成的 catch 块

    			e.printStackTrace();

    		}	

    		GUI("服务端");

    		while(true){

    			GetMsg();

    		}

    	}

    	

    	public static void main(String args[]){

    		new recevice();

    	}

    	

    	public void GUI(String str){ //图形化界面

    		this.setTitle(str);

    		Container container = this.getContentPane();

    		JButton send = new JButton("发送");

    		JLabel msg = new JLabel("消息内容");

    		Chat = new JTextArea();

    		Mes = new JTextField(20);

    		Chat.setEditable(false);

    		JScrollPane contain = new JScrollPane(); //滚动框

            contain.setViewportView(Chat);

            container.setLayout(new BorderLayout()); //设置布局方式

            container.add(contain,BorderLayout.CENTER);

            JPanel botton = new JPanel();

            Mes.addActionListener(this);

            send.addActionListener(this); //绑定监听

            botton.add(msg);

            botton.add(Mes);

            botton.add(send);

            container.add(botton,BorderLayout.SOUTH);

            this.show(true);

            this.setSize(600, 400);

    	}

    	//与Button绑定的方法

    	public void actionPerformed(ActionEvent e) {

    	  String str = Mes.getText();  //取得文本域的内容

    	  if(str.equals("")){

    		  Chat.append("提示:消息不可以为空!!!\n");

    	  }else{

    		  Chat.append("我说:"+str+"\n");

    		  //UDP发包

    		  SendMsg(str);

    	  }

    	  Mes.setText("");

    	}

    	

    	//发包

    	public void SendMsg(String str){

    		try {

    			DatagramPacket packet = new DatagramPacket(str.getBytes(),str.getBytes().length,adr,port);

    		    //DatagramSocket soc = new DatagramSocket();

    		    soc.send(packet);

    		} catch (Exception e) {

    			// TODO 自动生成的 catch 块

    			e.printStackTrace();

    		}		

    	}

    	

    	//接收

    	public void GetMsg(){

    		byte data[]= new byte[1024];

    		DatagramPacket packet = new DatagramPacket(data,1024);

    		try {		    	

    			soc.receive(packet);

    			adr=packet.getAddress();

    			port=packet.getPort();

    		} catch (IOException e) {

    			// TODO 自动生成的 catch 块

    			e.printStackTrace();

    		}

    		Chat.append("客户:"+new String(packet.getData(),0,packet.getData().length)+"\n");

    	}

    }

     
    -----------------------------------------------------------------------------------------------------------------------------------------
     
    //tcp实现
     

        <服务端>

    import java.awt.BorderLayout;

    import java.awt.Container;

    import java.awt.event.ActionEvent;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    import java.io.IOException;

    import java.net.ServerSocket;

    import java.net.Socket;

    import javax.swing.Action;

    import javax.swing.JButton;

    import javax.swing.JFrame;

    import javax.swing.JLabel;

    import javax.swing.JPanel;

    import javax.swing.JScrollPane;

    import javax.swing.JTextArea;

    import javax.swing.JTextField;

    public class getmsg extends JFrame implements Action{

    	private JTextArea Chat ;

    	private JTextField sms ;

    	private ServerSocket serverSocket ;

    	private Socket socket;

    	DataInputStream in;

    	public static void main(String[] args) {

    		new getmsg();

    	}

    	

    	public getmsg() {

           GUI("服务端");

           try {

    			serverSocket = new ServerSocket(20000);

    		} catch (IOException e1) {

    			// TODO Auto-generated catch block

    			e1.printStackTrace();

    		}

           try {

        	  socket = new Socket();

        	  socket = serverSocket.accept();

    		in = new DataInputStream(socket.getInputStream());

    	} catch (IOException e) {

    		// TODO Auto-generated catch block

    		e.printStackTrace();

    	}

    	 

          new getmes().start();

    	}

    	/**

    	 * 获取消息线程

    	 */

    	class getmes extends Thread{

    		@Override

    		public void run() {

    			super.run();

    			

    			while(true){

    				try {

    					

    					  Chat.append("对方: >"+in.readUTF()+"\n");

    					  //in.close();

    					  

    				} catch (Exception e) {

    					// TODO Auto-generated catch block

    					e.printStackTrace();

    				}

    		}

    	}

    	}

    	

    	/**

    	 * 发送消息线程

    	 */

    	

    	class sendmes extends Thread{

    		@Override

    		public void run() {

    			super.run();

    			System.out.println("发送线程");

    			DataOutputStream out;

    			try {

    				out = new DataOutputStream(socket.getOutputStream());

    				//System.out.println(">>>>"+socket.isClosed());

    				//System.out.println(">>>>"+sms.getText().trim());

    				out.writeUTF(sms.getText().trim());

    				//out.close();

    				Chat.append("我: >"+sms.getText().trim()+"\n");

    				sms.setText("");

    			} catch (IOException e) {

    				// TODO Auto-generated catch block

    				e.printStackTrace();

    			}

    		}

    	}

    	public void GUI(String title){

    		this.setTitle(title);

    		Container container = this.getContentPane();

    		Chat = new JTextArea(); //内容显示框

    		JScrollPane center = new JScrollPane(); //滚动版

    		sms = new JTextField(20);

    		JButton send = new JButton("发送");

    		JLabel mes = new JLabel("输入消息:");

    		container.setLayout(new BorderLayout());

    		center.setViewportView(Chat);

    		Chat.setEditable(false);

    		container.add(center);

    		JPanel bottom = new JPanel();

    		bottom.add(mes);

    		bottom.add(sms);

    		bottom.add(send);

    		container.add(bottom,BorderLayout.SOUTH);		

    		this.setSize(600, 400);

    		this.show(true);		

    		send.addActionListener(this); //设置监听

    	}

    	@Override

    	public void actionPerformed(ActionEvent e) {

    		// TODO Auto-generated method stub

    		new sendmes().start();

    		System.out.println(socket.isClosed());

    	}

    	@Override

    	public Object getValue(String key) {

    		// TODO Auto-generated method stub

    		return null;

    	}

    	@Override

    	public void putValue(String key, Object value) {

    		// TODO Auto-generated method stub

    		

    	}

    }

     
     
     
     
     

        <客户端>

    import java.awt.BorderLayout;

    import java.awt.Container;

    import java.awt.event.ActionEvent;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    import java.io.IOException;

    import java.net.ServerSocket;

    import java.net.Socket;

    import java.net.UnknownHostException;

    import javax.swing.Action;

    import javax.swing.JButton;

    import javax.swing.JFrame;

    import javax.swing.JLabel;

    import javax.swing.JPanel;

    import javax.swing.JScrollPane;

    import javax.swing.JTextArea;

    import javax.swing.JTextField;

    public class send extends JFrame implements Action{

    	private JTextArea Chat ;

    	private JTextField sms ;

    	private Socket socket;

    	private DataOutputStream out;

    	private DataInputStream  in;

    	public static void main(String[] args) {

    		new send();

    	}

    	

    	public send() {

    		GUI("客户端");

    		try {

    			socket = new Socket("192.168.56.1", 20000);

    			

    			in= new DataInputStream(socket.getInputStream());

    		} catch (UnknownHostException e) {

    			// TODO Auto-generated catch block

    			e.printStackTrace();

    		} catch (IOException e) {

    			// TODO Auto-generated catch block

    			e.printStackTrace();

    		}

    		//开启新线程

    		new rec().start();

            

            

    	}

    	

    	/**

    	 * 接收线程

    	 */

    	class rec extends Thread{

    		@Override

    		public void run() {

    			super.run();

    			while(true){

    			try{

    		  

    		  Chat.append("对方: >"+in.readUTF()+"\n");

    		

    		}catch(Exception exception){}

    			}

    	}

    	}

    	

    	/**

    	 * 发送线程

    	 */

    	class sendmsg extends Thread{

    		@Override

    		public void run() {

    			super.run();

    			

    			try {	

    				

    				System.out.println(">>>>"+socket.getPort()+">>"+socket.getLocalAddress().toString());

    				out = new DataOutputStream(socket.getOutputStream());

    				out.writeUTF(sms.getText().trim());

    				//out.close();

    				Chat.append("我: >"+sms.getText().trim()+"\n");

    				sms.setText("");

    			} catch (IOException e) {

    				// TODO Auto-generated catch block

    				e.printStackTrace();

    			}

    			

    		}

    	}

    	/**

    	 * 图形端

    	 */

    	public void GUI(String title){

    		this.setTitle(title);

    		Container container = this.getContentPane();

    		Chat = new JTextArea(); //内容显示框

    		JScrollPane center = new JScrollPane(); //滚动版

    		sms = new JTextField(20);

    		JButton send = new JButton("发送");

    		JLabel mes = new JLabel("输入消息:");

    		container.setLayout(new BorderLayout());

    		center.setViewportView(Chat);

    		Chat.setEditable(false);

    		container.add(center);

    		JPanel bottom = new JPanel();

    		bottom.add(mes);

    		bottom.add(sms);

    		bottom.add(send);

    		container.add(bottom,BorderLayout.SOUTH);		

    		this.setSize(600, 400);

    		this.show(true);		

    		send.addActionListener(this); //设置监听

    	}

    	@Override

    	public void actionPerformed(ActionEvent e) {

    		// TODO Auto-generated method stub

    		System.out.println("Onclick");

    		new sendmsg().start(); //发送信息启动新线程

    	}

    	@Override

    	public Object getValue(String key) {

    		// TODO Auto-generated method stub

    		return null;

    	}

    	@Override

    	public void putValue(String key, Object value) {

    		// TODO Auto-generated method stub

    		

    	}

    }

     
     


[Java] Tcp/udp 简单通信,布布扣,bubuko.com

[Java] Tcp/udp 简单通信

标签:tcp   java   udp   通信   图形   

原文地址:http://blog.csdn.net/guozeyiblog/article/details/37822043

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!