一、概述
TCP(传输控制协议)和UDP(用户数据报协议是网络体系结构TCP/IP模型中传输层一层中的两个不同的通信协议。
TCP:传输控制协议,一种面向连接的协议,给用户进程提供可靠的全双工的字节流,TCP套接口是字节流套接口(stream socket)的一种。
UDP:用户数据报协议。UDP是一种无连接协议。UDP套接口是数据报套接口(datagram socket)的一种。
二、简单了解了社么是TCP和UDP是什么之后,我们就来具体实现基于Socket的编程实现:
TCP通信
TCPService.java TCP的服务端
package sockettest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/** * TCP服务端 * @author wjddn * */
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8796);
System.out.println("****服务器正在启动,等待数据传输******");
Socket socket =null;
int count = 0;
while(true){
socket = serverSocket.accept();
ServerThread thread = new ServerThread(socket);
thread.start();
count++;
System.out.println("当前访客为: "+count);
InetAddress address = socket.getInetAddress();
System.out.println("当前客户端的ip为: "+address.getHostAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCPClient.java TCP客户端
package sockettest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/** * 客户端 * @author wjddn * */
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost",8796);
OutputStream stream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(stream);
writer.write("用户名:hansan , 密码:456");
writer.flush();
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String date = null;
while((date = reader.readLine())!=null){
System.out.println(date);
}
inputStream.close();
reader.close();
stream.close();
writer.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
因为想了下,通信是有交互的,所以这里使用多线程来进行客户端与服务器端的交互。
package sockettest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/** * 多线程实现Socket * @author wjddn * */
public class ServerThread extends Thread {
Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
};
@Override
public void run() {
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
OutputStream stream = null;
PrintWriter writer = null;
try {
inputStream = socket.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String info = null;
while((info = bufferedReader.readLine())!=null){
System.out.println(info);
}
socket.shutdownInput();
stream = socket.getOutputStream();
writer = new PrintWriter(stream);
writer.write("这里是服务端发来的信息,欢迎你......");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(stream != null){
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}finally{
stream = null;
}
}
if(writer != null){
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
writer = null;
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
inputStream = null;
}
}
if(inputStreamReader != null){
try {
inputStreamReader.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
inputStreamReader = null;
}
}
if(socket != null){
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
socket = null;
}
}
}
}
}
以上就是多线程实现TCP服务端与客户端进行通讯。在验证时候先启动服务端,再启动客户端。
UDP通讯
udp通信利用的是一个DatagreamSocket类进行实现的,具体代码如下:
UDPServer.java
package sockettest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/** * UDP通信服务端 * @author wjddn * */
public class UDPServer {
public static void main(String[] args) {
try {
/** * 接收客户端信息 */
DatagramSocket socket = new DatagramSocket(8888);
byte [] date = new byte[1024];
DatagramPacket packet = new DatagramPacket(date,date.length);
socket.receive(packet);
System.out.println("客户端说:"+new String(date, 0,packet.getLength()));
/** * 向客户端发送信息 */
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte [] date2 = "欢迎你....".getBytes() ;
DatagramPacket datagramPacket = new DatagramPacket(date2, date2.length, address, port);
socket.send(datagramPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDPClient.java
package sockettest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/** * UDP客户端 * * @author wjddn * */
public class UDPClient {
public static void main(String[] args) {
try {
/** * 向服务器发送数据 */
// 定义服务器地址
InetAddress address = InetAddress.getByName("localhost");
int port = 8888;
byte[] date = "用户名: admin ,密码 : admin".getBytes();
DatagramPacket packet = new DatagramPacket(date, date.length,
address, port);
// 创建DatagreamSocket对象
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
/** * 接收服务器信息 */
byte[] date2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(date2, date2.length);
socket.receive(packet2);
System.out.println("服务器说: "
+ new String(date2, 0, packet2.getLength()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}