如果你对JavaSocket依然陌生,看看这个最简单的例子.

下面程序实现利用 Socket 套接字进行面向连接通信的编程。客户端读取本地文件并发送;服务器接收文件并保存到本地文件系统中。

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 客户端
 * 
 * @author Kree
 */
public class Client {
    public static void main(String[] args ) throws Exception {
 Socket client = new Socket("localhost", 8888);
 InputStream fis = new FileInputStream(new File("d:/table1.txt"));
 OutputStream out = client.getOutputStream();

 int n = 0;
 while ((n = fis.read()) != -1) {
     out.write(n);
 }
 fis.close();
 out.close();
    }
}

 

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

/**
 * 服务器端
 * 
 * @author Kree
 */
public class Server {
    public static void main(String[] args ) throws Exception {
 ServerSocket server = new ServerSocket(8888);
 Socket recive = server.accept();
 InputStream in = recive.getInputStream();
 OutputStream fos = new FileOutputStream("d:/abc.txt");

 int n = 0;
 while ((n = in.read()) != -1) {
     fos.write(n);
 }
 fos.flush();
 in.close();
 fos.close();
    }
} 

 

你可能感兴趣的:(java,编程,.net,socket)