TCP:
1.TCP服务端:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(5000);// 创建TCP连接
Socket s = ss.accept();// 阻塞接收client
InputStream is = s.getInputStream();// 提取输入流
byte[] buf = new byte[1024];
is.read(buf, 0, buf.length); // 将输入流的信息读出到buf
String mes = new String(buf);
System.out.println(mes);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ss != null) {
ss.close();// 用完就关闭
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.TCP客户端:
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient {
public static void main(String[] args) {
Socket s = null;
try {
s = new Socket("127.0.0.1", 5000);// 创建TCP连接
OutputStream os = s.getOutputStream();// 从中获取输出流
os.write("你好".getBytes());// 输出信息
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (s != null) {// 用完就关闭
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UDP
3.UDP服务端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPServer {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(5000); //创建UDP连接
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length); //将数据拆包到buf
ds.receive(dp); //阻塞接收client发过来的数据包
String mes = new String(buf);
System.out.println(mes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ds !=null) {
ds.close(); //关闭
}
}
}
}
4.UDP客户端:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UDPClient {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(); //创建UDP连接
byte[] buf = "你好么".getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length,
new InetSocketAddress("127.0.0.1", 5000)); //将数据打好包,并指定数据包 送到哪里
ds.send(dp);//将数据报包发送
} catch (IOException e) {
e.printStackTrace();
} finally {
ds.close();//关闭
}
}
}