本文转载自:http://wing011203.cnblogs.com/

在这篇文章里,我们主要讨论如何使用Java实现网络通信,包括TCP通信、UDP通信、多播以及NIO。

  TCP连接

  TCP的基础是Socket,在TCP连接中,我们会使用ServerSocket和Socket,当客户端和服务器建立连接以后,剩下的基本就是对I/O的控制了。

  我们先来看一个简单的TCP通信,它分为客户端和服务器端。

  客户端代码如下:

简单的TCP客户端
import java.net.*;
import java.io.*;
public class SimpleTcpClient {

    public static void main(String[] args) throws IOException
    {
        Socket socket = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        BufferedReader brTemp = null;
        try
        {
            socket = new Socket(InetAddress.getLocalHost(), 5678);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            pw = new PrintWriter(socket.getOutputStream());
            brTemp = new BufferedReader(new InputStreamReader(System.in));
            while(true)
            {
                String line = brTemp.readLine();
                pw.println(line);
                pw.flush();
                if (line.equals("end")) break;
                System.out.println(br.readLine());
            }
        }
        catch(Exception ex)
        {
            System.err.println(ex.getMessage());
        }
        finally
        {
            if (socket != null) socket.close();
            if (br != null) br.close();
            if (brTemp != null) brTemp.close();
            if (pw != null) pw.close();
        }
    }
}
简单的TCP客户端

相关文章: