java Socket使用

这是一个服务端的监听示例:
public class Test {
	
	public static void main(String[] args) {
		Test1 t=new Test1();
		t.start();   //启动线程
	}

}
/**
 * 继承一个线程类
 * @author Administrator
 *
 */
class Test1 extends Thread{
	private ServerSocket server = null;
	public Test1(){
		try {
			server=new ServerSocket(3333);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("服务端初始化scoket失败!");
		}
	}
	/**
	 * 继承父类方法
	 */
	public void run(){
		Socket clientSocket = null;
		DataInputStream dis =null;
		DataOutputStream dos=null;
		String str="";
		while(true){
			try {
				 clientSocket=server.accept();
				 dis = new DataInputStream(clientSocket.getInputStream());//获取输入流,用于接收客户端发送来的数据
                                dos = new DataOutputStream(clientSocket.getOutputStream());//获取输出流,用于客户端向服务器端发送数据
				 str=dis.readUTF();  //这里是客户端发送来的数据
				 /*
				  * 这里边你就可以做你想操作的事情了
				  */
                                 dos.writeUTF("这里是返回到客户端的数据");//这里用来向客户端返回数据
				 dis.close();
                                 dos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
以下是一个完整的服务端客户端的socket连接示例,我用这个方法使得客户端向服务端发送文件,服务端接受文件并保存在本地:
<pre name="code" class="java">这是服务端代码:
package com.SegAndClassificationSys;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
*
* 文件名:ZServerReceive.java
* 实现功能:作为服务器接收客户端发送的文件
*
* 具体实现过程:
* 1、建立SocketServer,等待客户端的连接
* 2、当有客户端连接的时候,按照双方的约定,这时要读取一行数据
* 其中保存客户端要发送的文件名和文件大小信息
* 3、根据文件名在本地创建文件,并建立好流通信
* 4、循环接收数据包,将数据包写入文件
* 5、当接收数据的长度等于提前文件发过来的文件长度,即表示文件接收完毕,关闭文件
* 6、文件接收工作结束
**/

public class ZServerReceive extends Thread{
	
	private int FileID = 0;
	
	/** 路径格式: ./xxx.txt*/
	public File newFile(String path) {
		File file = new File(path);
		return file;
	}

	public void run() {

		/**与服务器建立连接的通信句柄*/
		ServerSocket ss = null;
		Socket s = null;

		/**定义用于在接收后在本地创建的文件对象和文件输出流对象*/
		File file = null;
		FileOutputStream fos = null;

		/**定义输入流,使用socket的inputStream对数据包进行输入*/
		InputStream is = null;

		/**定义byte数组来作为数据包的存储数据包*/
		byte[] buffer = new byte[4096 * 5];

		/**用来接收文件发送请求的字符串*/
		String comm = null;

		/**建立socket通信,等待服务器进行连接*/
		try {
			ss = new ServerSocket(4004);
		} catch (IOException e) {
			e.printStackTrace();
		}
		while(true) {
			
			try {
				s = ss.accept();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			/**读取一行客户端发送过来的约定信息*/
			try {
				InputStreamReader isr = new InputStreamReader(s.getInputStream());
				BufferedReader br = new BufferedReader(isr);
				comm = br.readLine();
			} catch (IOException e) {
				System.out.println("服务器与客户端断开连接");
			}

			/**开始解析客户端发送过来的请求命令*/
			int index = comm.indexOf("/#");

			/**判断协议是否为发送文件的协议*/
			String xieyi = comm.substring(0, index);
			if(!xieyi.equals("111")){
				System.out.println("服务器收到的协议码不正确");
				return;
			}

			/**解析出文件的名字和大小*/
			comm = comm.substring(index + 2);
			index = comm.indexOf("/#");
			String filename = comm.substring(0, index).trim();
			String filesize = comm.substring(index + 2).trim();

			/**创建空文件,用来进行接收文件*/
			file = newFile("D:/" + filename.substring(0, filename.lastIndexOf(".") - 1) + FileID + ".txt");
			//file = new File("D:/Content.txt");
			System.out.println("服务器中文件路径:" + file.getPath());
			
			if(!file.exists()){
				try {
					file.createNewFile();
				} catch (IOException e) {
					System.out.println("服务器端创建文件失败");
				}
			}else{
				/**在此也可以询问是否覆盖*/
				System.out.println("本路径已存在相同文件,进行覆盖");
			}
			// File的ID号自增,为了标明每个独特的file
			FileID ++;

			/**【以上就是客户端代码中写到的服务器的准备部分】*/

			/**
			 * 服务器接收文件的关键代码*/
			try {
				/**将文件包装到文件输出流对象中*/
				fos = new FileOutputStream(file);
				long file_size = Long.parseLong(filesize);
				is = s.getInputStream();
				/**size为每次接收数据包的长度*/
				int size = 0;
				/**count用来记录已接收到文件的长度*/
				long count = 0;

				/**使用while循环接收数据包*/
				while(count < file_size){
					/**从输入流中读取一个数据包*/
					size = is.read(buffer);

					/**将刚刚读取的数据包写到本地文件中去*/
					fos.write(buffer, 0, size);
					fos.flush();

					/**将已接收到文件的长度+size*/
					count += size;
					System.out.println("服务器端接收到数据包,大小为" + size);
				}
				System.out.println("文件接受完毕!");

			} catch (FileNotFoundException e) {
				System.out.println("服务器写文件失败");
			} catch (IOException e) {
				System.out.println("服务器:客户端断开连接");
			}finally{
				/**
				 * 将打开的文件关闭
				 * 如有需要,也可以在此关闭socket连接
				 * */
				try {
					if(fos != null)
						fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}//catch (IOException e)
			}//finally
		}
	}//public static void main(String[] args)
}//public class ServerReceive

这是客户端代码:
 
<pre name="code" class="java">package com.SegAndClassificationSys;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
*
* 文件名:ClientSend.java
* 实现功能:作为客户端向服务器发送一个文件
*
* 具体实现过程:
* 1、建立与服务器端的连接,IP:127.0.0.1, port:4004
* 2、将文件的名字和大小通过自定义的文件传输协议,发送到服务器
* 3、循环读取本地文件,将文件打包发送到数据输出流中
* 4、关闭文件,结束传输
*
* */

public class ZClientSend extends Thread{
	private String path;
	
	public ZClientSend(String p) {
		path = p;
	}

	public void run() {
		
		/**开启服务器测试*/
		//ZServerReceive zsr = new ZServerReceive();
		//zsr.start();
		
		/**与服务器建立连接的通信句柄*/
		Socket s = null;

		/**定义文件对象,即为要发送的文件
		 * 如果使用绝对路径,不要忘记使用'/'和'\'的区别
		 * 具体区别,请读者自行查询
		 * */
		File sendfile = new File(path);
		/**定义文件输入流,用来打开、读取即将要发送的文件*/
		FileInputStream fis = null;
		/**定义byte数组来作为数据包的存储数据包*/
		byte[] buffer = new byte[4096 * 5];

		/**定义输出流,使用socket的outputStream对数据包进行输出*/
		OutputStream os = null;

		/**检查要发送的文件是否存在*/
		if(!sendfile.exists()){
			System.out.println("客户端:要发送的文件不存在");
			return;
		}

		/**与服务器建立连接*/
		try {
			s = new Socket("127.0.0.1", 4004);
		}catch (IOException e) {
			System.out.println("未连接到服务器");
		}

		/**用文件对象初始化fis对象
		 * 以便于可以提取出文件的大小
		 * */
		try {
			fis = new FileInputStream(sendfile);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		/**首先先向服务器发送关于文件的信息,以便于服务器进行接收的相关准备工作
		 * 具体的准备工作,请查看服务器代码。
		 *
		 * 发送的内容包括:发送文件协议码(此处为111)/#文件名(带后缀名)/#文件大小
		 * */
		try {
			PrintStream ps = new PrintStream(s.getOutputStream());
			ps.println("111/#" + sendfile.getName() + "/#" + fis.available());
			ps.flush();
		} catch (IOException e) {
			System.out.println("服务器连接中断");
		}

		/**
		 * 此处睡眠2s,等待服务器把相关的工作准备好
		 * 也是为了保证网络的延迟
		 * 读者可自行选择添加此代码
		 * */
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		/**之前的准备工作结束之后
		 * 下面就是文件传输的关键代码
		 * */
		try {

			/**获取socket的OutputStream,以便向其中写入数据包*/
			os = s.getOutputStream();

			/** size 用来记录每次读取文件的大小*/
			int size = 0;

			/**使用while循环读取文件,直到文件读取结束*/
			while((size = fis.read(buffer)) != -1){
				System.out.println("客户端发送数据包,大小为" + size);
				/**向输出流中写入刚刚读到的数据包*/
				os.write(buffer, 0, size);
				/**刷新一下*/
				os.flush();
			}
		} catch (FileNotFoundException e) {
			System.out.println("客户端读取文件出错");
		} catch (IOException e) {
			System.out.println("客户端输出文件出错");
		}finally{

			/**
			 * 将打开的文件关闭
			 * 如有需要,也可以在此关闭socket连接
			 * */
			try {
				if(fis != null)
					fis.close();
			} catch (IOException e) {
				System.out.println("客户端文件关闭出错");
			}//catch (IOException e)
		}//finally

	}//public static void main(String[] args)
}//public class ClientSend



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值