一、             TCP编程:

ServerSocket用于服务器端,Socket用于客户端。

1、一个简单的示例向客户端发送内容:

import java.io.OutputStream;

import java.io.PrintStream;

import java.net.*;

public class TcpDemo1 {

   public static void main(String[] args) throws Exception{

     ServerSocket server=new ServerSocket(8888);//在8888端口上开启服务

     Socket client=null;

     System.out.println("等待连接...");

     client=server.accept();//等待客户端连接

     OutputStream out=client.getOutputStream();//得到客户端输出流

     PrintStream pout=new PrintStream(out);

     pout.print("hello world");//向客户端输出内容

     pout.close();

     out.close();

     client.close();

     server.close();

     System.out.println("信息已发送!");

   }

 

}

2、读取客户端输入的内容:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.*;

public class TcpDemo2 {

   public static void main(String[] args) throws Exception{

     ServerSocket server=new ServerSocket(8888);//在8888端口上开启服务

     Socket client=null;

     System.out.println("等待连接...");

     client=server.accept();//等待客户端连接

     BufferedReader buf=new BufferedReader(

          new InputStreamReader(client.getInputStream()));//得到客户端输入流

     char[] cs=new char[1024];

     int len=buf.read(cs);    

     System.out.println(new String(cs,0,len));

     buf.close();

     client.close();

     server.close();

     System.out.println("信息已发送!");

   }

 

}

二、UDP编程:

UDP主要使用以下两个类:

数据报内容:DatagramPacket

发送和接受内容:DatagramSocket

先运行客户端,在运行服务器端。

客户端接收数据代码:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

 

 

public class TcpClient {

   public static void main(String[] args) throws Exception {

     DatagramSocket socket=new DatagramSocket(3000);

     DatagramPacket pack=new DatagramPacket(new byte[1024],1024);

     socket.receive(pack);

     System.out.println(new String(pack.getData()));

   }

 

}

服务器端发送数据代码:

package org.demo;

 

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

 

 

public class TcpServer {

   public static void main(String[] args) throws Exception {

     DatagramSocket socket=new DatagramSocket(9000);

     String str="hello world";

     DatagramPacket pack=new DatagramPacket(str.getBytes(),

           0,str.length(),InetAddress.getLocalHost(),3000);

     socket.send(pack);

   }

 

}