您的位置:首页 > 理论基础 > 计算机网络

Socket连接实例(TCP/UDP)

2009-07-07 16:47 423 查看
1 服务器建立了一个监听指定端口号的服务器端Socket连接

2 客户端发送连接

3 服务器为每一个连接启动一个新的线程

4 信息交换

5 关闭连接

服务器:

package net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MulSocketServer {

public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
OutputStream os = null;// 输出流
InputStream is = null;// 输入流
int port = 10000;// 监听端口号

try {
serverSocket = new ServerSocket(port);
System.out.println(":已经启动");
while (true) {// 接收到一个连接、启动一个线程
socket = serverSocket.accept();
new LogicThread(socket);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
os.close();
is.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
}
}
}
}

class LogicThread extends Thread {
Socket socket;
InputStream is;
OutputStream os;

public LogicThread(Socket socket) {
this.socket = socket;
start(); // 启动线程
}

public void run() {
byte[] b = new byte[1024];
try {
os = socket.getOutputStream();// 初始化流
is = socket.getInputStream();
for (int i = 0; i < 3; i++) {
int n = is.read(b);// 读取数据
byte[] response = logic(b, 0, n); // 逻辑处理
os.write(response); // 反馈数据
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}

/**
* 关闭流和连接
*/
private void close() {
try {
// 关闭流和连接
os.close();
is.close();
socket.close();
} catch (Exception e) {
}
}

/**
* 逻辑处理方法,实现echo逻辑
*
* @param b
*            客户端发送数据缓冲区
* @param off
*            起始下标
* @param len
*            有效数据长度
* @return
*/
private byte[] logic(byte[] b, int off, int len) {
byte[] response = new byte[len];
// 将有效数据拷贝到数组response中
System.arraycopy(b, 0, response, 0, len);
return response;
}
}


客户端:

package net;

import java.io.*;
import java.net.*;

public class MulSocketClient {
public static void main(String[] args) {
Socket socket = null;
InputStream is = null;
OutputStream os = null;
String serverIP = "127.0.0.1"; // 服务器端IP地址
int port = 10000; // 服务器端端口号
String data[] = { "First", "Second", "Third" }; // 发送内容

try {
socket = new Socket(serverIP, port); // 建立连接
os = socket.getOutputStream(); // 初始化流
is = socket.getInputStream();
byte[] b = new byte[1024];
for (int i = 0; i < data.length; i++) {
os.write(data[i].getBytes()); // 发送数据
int n = is.read(b); // 接收数据
System.out.println("服务器反馈:" + new String(b, 0, n)); // 输出反馈数据
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
socket.close();
} catch (Exception e2) {
}
}
}
}


一直没事动手敲敲 今天补上

UDP连接实例:

较TCP而言传输不可考,无需建立虚拟连接,服务器压力较小。

传输一般步骤:

客户端:

1 建立DatagramSocket连接

2 然后构造一个DatagramPacket对象,此对象包括内容,接收方IP,端口号。

3 用DatagramSocket对象的send()方法发送DatagramPacket数据包。

4 用DatagramSocket对象的receive()方法接收DatagramPacket返回的数据包。

5 关闭DatagramSocket连接

服务器端:

1 建立DatagramSocket连接,监听端口

2 使用DatagramSocket的receive()方法接收发来的数据

3 关闭连接

服务器端应为每一个连接起一个线程,方法同TCP的服务器端。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: