JAVA socket编程学习笔记
Socket是网络编程,而不是简单的网页编程,它与J2EE编写网页代码还是有很大的区别的,Socket更接近底层一点,所以难度稍稍大一点。
import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(3333); while(true){ Socket socket = serverSocket.accept(); System.out.println("接收了用户的请求"); ServerSendThread sst = new ServerSendThread(new TCPServer(),socket); Thread thread = new Thread(sst); thread.start(); } } catch (IOException e) { e.printStackTrace(); } } public void serverSend(Socket s){ OutputStream outputStream; try { outputStream = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputStream); dos.writeUTF("server sent data:huangbiao"); } catch (IOException e) { e.printStackTrace(); } } public void serverReceive(Socket s){ try { InputStream inputStream = s.getInputStream(); DataInputStream dis = new DataInputStream(inputStream); String temp = dis.readUTF(); System.out.println("server receive data is:" + temp); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TCPClient { public static final int PORT = 3333; public static final String IP = "127.0.0.1"; public static void main(String[] args) { try { Socket socket = new Socket(IP,PORT); ClientReceiveThread crt = new ClientReceiveThread(new TCPClient(),socket); Thread thread = new Thread(crt); thread.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void clientReceive(Socket s){ InputStream inputStream; try { inputStream = s.getInputStream(); DataInputStream dis = new DataInputStream(inputStream); String str = dis.readUTF(); System.out.println("client receive data is:"+str); } catch (IOException e) { e.printStackTrace(); } } public void clientSent(Socket s){ try { OutputStream outputStream = s.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputStream); dos.writeUTF("client sent data is huangbiao"); } catch (IOException e) { e.printStackTrace(); } } }
注意事项:
1、在Socket编程中,端口号尽量选择1024之后的端口号,因为在这之前很多端口号可能被很多知名的协议或者是网站占用了,所以为了降低冲突,选择不常用的端口号
2、TCP和UDP都有65535个端口,也就是说tcp 80 和 UDP 80端口是不一致的
3、client和server这两个只针对TCP协议而言,UDP协议是没有这个说法的,因为UDP只关注发送不管是否对方接收
4、server和client两端都可以读和写数据流,只有一端写了之后另一端才能读,我这样强调的目的是为了说明读写是有顺序的
回忆过去,珍惜现在,放眼未来