网络编程:ServerSocket、Socket
TCP协议
客户端:
public class TestClient {
public static void main(String[] args) throws Exception {
Socket sc = new Socket("127.0.0.1",8888);
BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
System.out.println(br.readLine());
sc.close();
br.close();
}

}
服务端:
public class TestServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8888);
System.out.println("等待客户端连接......");
Socket client = ss.accept();
PrintWriter pw = null;
String str = "今天天气好晴朗,适合打篮球呀";
pw = new PrintWriter(client.getOutputStream());
pw.print(str);
pw.close();
client.close();
ss.close();
}
}

UDP协议
发送端:
public class UdpSend {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "今天天气好晴朗,春天来了";
byte[] bys = str.getBytes();
InetAddress ia = InetAddress.getByName("192.168.1.102");
DatagramPacket dp = new DatagramPacket(bys,bys.length, ia, 2323);
ds.send(dp);
ds.close();
}

}
接受端:
public class UdpReceive {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(2323);
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength());
System.out.print(dp.getAddress().getHostName());
System.out.print(dp.getPort());
System.out.println(str);
}

}

UDP与TCP的区别:
UDP:
将数据及源和目的封装成数据包;每个数据包限制在64K方位内;是不可靠协议;不需要建立连接,速度快
TCP:
需要连接,建立传输数据的通道;在连接中进行大量数据传输;通过三次握手完成连接,是可靠协议;必须建立连接,效率稍微低些