Socket 2:Socket通信代码_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Socket 2:Socket通信代码

Socket 2:Socket通信代码

 2015/4/12 18:36:00  XiangdongLee  程序员俱乐部  我要评论(0)
  • 摘要:1.客户端向服务器端单向发送消息:(Client->Server)服务器端代码:packagecom.lxd.socket1;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.ServerSocket;importjava.net.Socket;/***1.客户端向服务器端单向发送消息:(Client->Server
  • 标签:socket通信 代码 socket
        1.客户端向服务器端单向发送消息:(Client -> Server)

        服务器端代码:
       
class="java" name="code">package com.lxd.socket1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 1.客户端向服务器端单向发送消息:(Client -> Server)
 * 
 * @author Xiangdong
 * 
 */

//服务器端
public class ServerDemo {
	public static void main(String[] args) {
		try {
			// 创建服务器对象,并指定端口号
			ServerSocket serverSocket = new ServerSocket(8087);
			System.out.println("服务器已启动...");

			// 监听并接收客户端的输入
			Socket socket = serverSocket.accept();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String s = br.readLine();
			System.out.println("来自客户端的消息:" + s);
			// 一次连接,要关掉
			socket.close();
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

        客户端代码:
       
package com.lxd.socket1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 1.客户端向服务器端单向发送消息:(Client -> Server)
 * 
 * @author Xiangdong
 * 
 */

//客户端
public class ClientDemo {
	public static void main(String[] args) {
		try {
			// 请求服务器:指定服务器IP和端口号
			// (要找服务器端的人,先找酒店("127.0.0.1"),再找房间(8087),然后就找到了。)
			Socket socket = new Socket("127.0.0.1", 8087);
			System.out.println("客户端请求服务器...");
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			out.println(br.readLine());
			out.close();
			socket.close();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


        2.客户端和服务器 双方通信一次(Client <-> Server)

        服务器端代码:
       
package com.lxd.socket2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 2.客户端和服务器 双方通信一次(Client <-> Server)
 * 
 * @author Xiangdong
 * 
 */

//服务器端
public class ServerDemo {
	public static void main(String[] args) {
		try {
			// 创建服务器对象,并指定端口号
			ServerSocket serverSocket = new ServerSocket(8088);
			System.out.println("服务器已启动...");

			// 服务器接收客户端的消息
			Socket socket = serverSocket.accept();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String fromClient = br.readLine();
			System.out.println("来自客户端的消息:" + fromClient);

			// 服务器向客户端发送消息
			System.out.println("\n请输入发送到客户端的消息:");
			br = new BufferedReader(new InputStreamReader(System.in));
			String toClient = br.readLine();
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			out.println(toClient);

			out.close();
			br.close();
			socket.close();
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

        客户端代码:
       
package com.lxd.socket2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 2.客户端和服务器 双方通信一次(Client <-> Server)
 * 
 * @author Xiangdong
 * 
 */

//客户端
public class ClientDemo {
	public static void main(String[] args) {
		try {
			// 请求服务器:指定服务器IP和端口号
			// (要找服务器端的人,先找酒店("127.0.0.1"),再找房间(8087),然后就找到了。)
			Socket socket = new Socket("127.0.0.1", 8088);
			System.out.println("请输入发送到服务器端的消息:");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			String toServer = br.readLine();
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			out.println(toServer);

			// 接收来自服务器端的消息
			br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String fromServer = br.readLine();
			System.out.println("来自服务器端的消息:" + fromServer);

			out.close();
			br.close();
			socket.close();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


        3.多次通信

        服务器端代码:
       
package com.lxd.socket3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 3.多次通信
 * 
 * @author Xiangdong
 * 
 */

// 服务器端
public class QQServer {
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(8089);
			System.out.println("QQ Server start up...");
			Socket socket = serverSocket.accept();

			BufferedReader brToClient = new BufferedReader(
					new InputStreamReader(System.in));

			BufferedReader brFromClient = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));

			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

			while (true) {
				// 等待客户端输入
				String fromClient = brFromClient.readLine();
				if (fromClient == null || fromClient.equalsIgnoreCase("bye")) {
					System.out.println("结束聊天");
					break;
				}
				System.out.println("来自客户端的消息:" + fromClient);

				String toClient = brToClient.readLine();
				// 向客户端输出
				out.println(toClient);
			}

			out.close();
			brToClient.close();
			brFromClient.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

        客户端代码:
       
package com.lxd.socket3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 3.多次通信
 * 
 * @author Xiangdong
 * 
 */

// 客户端
public class QQClient {
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("127.0.0.1", 8089);
			System.out.println("QQ Client start up...");

			BufferedReader brToServer = new BufferedReader(
					new InputStreamReader(System.in));

			BufferedReader brFromServer = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));

			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

			// 客户端先发起聊天
			String toServer = brToServer.readLine();
			out.println(toServer);

			while (true) {
				// 等待服务器端输入
				String fromServer = brFromServer.readLine();
				if (fromServer == null || fromServer.equalsIgnoreCase("bye")) {
					System.out.println("结束聊天");
					break;
				}
				System.out.println("来自服务器端的消息:" + fromServer);

				toServer = brToServer.readLine();
				// 向服务器端输出
				out.println(toServer);
			}

			out.close();
			brToServer.close();
			brFromServer.close();
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


        4.创建线程,进行文件的双向传输

        线程类:
       
package com.lxd.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.Socket;

public class ServerFileThread extends Thread {
	private Socket socket;

	public ServerFileThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			DataInputStream inputStream = null;
			try {
				inputStream = new DataInputStream(new BufferedInputStream(
						socket.getInputStream()));
			} catch (Exception e) {
				System.out.print("接收消息缓存错误\n");
				return;
			}
			try {
				// 本地保存路径,文件名会自动从服务器端继承而来最好是web工程里的一个路径。
				String savePath = "E:\\";
				int bufferSize = 8192;
				byte[] buf = new byte[bufferSize];
				long len = 0;
				savePath += inputStream.readUTF();

				DataOutputStream fileOut = new DataOutputStream(
						new BufferedOutputStream(new BufferedOutputStream(
								new FileOutputStream(savePath))));
				len = inputStream.readLong();
				System.out.println("文件的长度为:" + len + "\n");
				System.out.println("开始接收文件!" + "\n");
				while (true) {
					int read = 0;
					if (inputStream != null) {
						read = inputStream.read(buf);
					}
					if (read == -1) {
						break;
					}
					// System.out.println(buf.toString());
					fileOut.write(buf, 0, read);
				}
				System.out.println("接收完成,文件存为" + savePath + "\n");
				fileOut.flush();
				fileOut.close();
				inputStream.close();
			} catch (Exception e) {
				System.out.println("接收消息错误" + "\n");
				return;
			}
		} catch (Exception e) {
			System.out.println("Error handling a client: " + e);
		}
	}
}

        服务器端代码:
       
package com.lxd.file;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketFileServer {
	protected int listenPort = 3000;

	/**
	 * 建立链接
	 * 
	 */
	public void acceptConnections() {
		try {
			ServerSocket server = new ServerSocket(listenPort);
			Socket socket = null;
			while (true) {
				socket = server.accept();
				// handleConnection(socket);
				new ServerFileThread(socket).start();
			}
		} catch (BindException e) {
			System.out.println("Unable to bind to port " + listenPort);
		} catch (IOException e) {
			System.out.println("Unable to instantiate a ServerSocket on port: "
					+ listenPort);
		}
	}

	public static void main(String[] args) {
		SocketFileServer server = new SocketFileServer();
		server.acceptConnections();
	}
}

        客户端代码:
       
package com.lxd.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketFileClient {
	protected String hostIp = "127.0.0.1";
	protected int hostPort = 3000;
	InputStream fis;
	DataOutputStream ps;
	File fi;
	DataInputStream dis;
	String path;
	Socket client;

	public SocketFileClient() {

	}

	public SocketFileClient(String path) {
		this.path = path;
	}

	public SocketFileClient(String path, String hostIp, int hostPort) {
		this.path = path;
		this.hostIp = hostIp;
		this.hostPort = hostPort;
	}

	public void run() {
		sendMessage();
	}

	/**
	 * 将连接到远程服务器
	 */
	public void setUpConnection() {
		try {
			client = new Socket(hostIp, hostPort);
			fis = new FileInputStream(path);
			ps = new DataOutputStream(client.getOutputStream());
			fi = new File(path);
		} catch (UnknownHostException e) {
			System.out
					.println("Error setting up socket connection: unknown host at "
							+ hostIp + ":" + hostPort);
		} catch (IOException e) {
			System.out.println("Error setting up socket connection: " + e);
		}

	}

	/**
	 * 将向远程服务器请求 path 的内容
	 * 
	 * @param path
	 * @return
	 */
	public void sendMessage() {
		setUpConnection();
		if (client == null)
			return;
		try {
			// 将文件名及长度传给客户端。
			ps.writeUTF(fi.getName());
			ps.flush();

			ps.writeLong((long) fi.length());
			ps.flush();
			int bufferSize = 8192;
			byte[] buf = new byte[bufferSize];
			while (true) {
				int read = 0;
				if (fis != null) {
					read = fis.read(buf);
				}
				if (read == -1) {
					break;
				}
				ps.write(buf, 0, read);
			}
			ps.flush();

			System.out.println("文件传输完成");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 注意关闭socket链接哦,不然客户端会等待server的数据过来,
			// 直到socket超时,导致数据不完整。
			try {
				ps.close();
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		String path = "src/ice.rmvb"; // 测试文件
		SocketFileClient client = new SocketFileClient(path);
		client.sendMessage();
	}
}
发表评论
用户名: 匿名