首先是基于TCP的socket编程
package primary;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
public class TCPSocket {
@Test
public void Client() {
Socket s = null;
OutputStream os = null;
InputStream is = null;
try {
s = new Socket(InetAddress.getByName("127.0.0.1"), 8989);// 客户端Socket,指定服务端IP和端口号
os = s.getOutputStream();
os.write("你好,服务器!".getBytes()); // 要输出的数据
s.shutdownOutput(); // 数据输出完毕
is = s.getInputStream();
int len = 0;
byte[] b = new byte[8];
while ((len = is.read(b)) != -1) {
System.out.print(new String(b, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void Server() {
ServerSocket ss = null;
Socket s = null;
OutputStream os = null;
try {
ss = new ServerSocket(8989); // 服务端Socket指定端口即可
s = ss.accept();
InputStream is = s.getInputStream();
byte[] b = new byte[8];
int len = 0;
while ((len = is.read(b)) != -1) {
System.out.print(new String(b, 0, len));
}
os = s.getOutputStream();
os.write("我已收到你的信息".getBytes());
s.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
基于UDP的Socket编程
package primary;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.junit.Test;
public class UDPSocket {
@Test
public void Send() {// 发送端
DatagramSocket ds = null; // 数据报套接字
try {
ds = new DatagramSocket();
byte[] b = "你好,我是要传输的数据".getBytes();
// 数据报包,包含要发送的数据,发送的地址及程序端口号
DatagramPacket dp = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 8989);
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
@Test
public void receive() {// 接收端
DatagramSocket ds = null;
try {
ds = new DatagramSocket(8989);
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, 0, b.length);
ds.receive(dp);
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
}
TCP传输需经历“三次握手”,安全,但效率要低于UDP