huakaile 发表于 2013-1-28 18:09:44

TCP Socket

1、TCP:是专门设计用于在不可靠的英特网上提供可靠的、端到端的字节流通信的协议,它是一个面向连接的协议,TCP连接是字节流而非报文流

                2、Socket:两个Java应用程序可通过一个双向的网络通信连接实现数据交换,这个双向链路的一端称为一个Socket、Socket通常用来实现client—server连接、java.net包中定义的两个Socket和ServerSocket,分别用来实现双向连接的client和server端、建立连接时所需的寻址信息为远程计算机的IP地址和端口号(Port number)——TCP端口 UDP端口分开,每一个65536个端口
import java.net.*;import java.io.*;public class TCPClient {public static void main(String[] args) throws Exception {Socket s = new Socket("127.0.0.1", 6666);OutputStream os = s.getOutputStream();//得到输出管道DataOutputStream dos = new DataOutputStream(os);//创建数据传输流Thread.sleep(30000);dos.writeUTF("hello server!");//客户端传输数据dos.flush();dos.close();s.close();}}
import java.net.*;import java.io.*;public class TCPServer {public static void main(String[] args) throws Exception {ServerSocket ss = new ServerSocket(6666);//在6666端口监听,准备连接客户端while (true) {Socket s = ss.accept();System.out.println("a client connect!");DataInputStream dis = new DataInputStream(s.getInputStream());//服务器通过输入管道接收数据流System.out.println(dis.readUTF());//输出读入的数据dis.close();s.close();}}}
import java.net.*;import java.io.*;public class TestSockClient {public static void main(String[] args) {    InputStream is = null; OutputStream os = null;    try {      Socket socket = new Socket("localhost",5888);      is = socket.getInputStream();//得到输入管道      os = socket.getOutputStream();//得到输出管道      DataInputStream dis = new DataInputStream(is);//创建输入流      DataOutputStream dos = new DataOutputStream(os); //创建输出流      dos.writeUTF("hey");   //向服务器写      String s = null;      if((s=dis.readUTF())!=null); //从服务器读      System.out.println(s);      dos.close();      dis.close();      socket.close();    } catch (UnknownHostException e) {       e.printStackTrace();    } catch (IOException e) {e.printStackTrace();}}}
import java.io.*; import java.net.*;public class TestSockServer {public static void main(String[] args) {    InputStream in = null;   OutputStream out = null;    try {      ServerSocket ss = new ServerSocket(5888);      Socket socket = ss.accept(); //得到输入管道      in = socket.getInputStream();       out = socket.getOutputStream();//得到输出管道      DataOutputStream dos = new DataOutputStream(out);//创建输出流      DataInputStream dis = new DataInputStream(in);   //创建输入流      String s = null;      if((s=dis.readUTF())!=null) {   //从客户端读入      System.out.println(s);      System.out.println("from: "+socket.getInetAddress()); //获取IP      System.out.println("Port: "+socket.getPort());//获取端口    }      dos.writeUTF("hi,hello");//向客户端写      dis.close();      dos.close();      socket.close();    } catch (IOException e) {e.printStackTrace();}}}
页: [1]
查看完整版本: TCP Socket