首页 > 代码库 > SocketServer 服务器
SocketServer 服务器
package com.boco.socketTest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
// 使用 OutputStreamWriter
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8765);
System.out.println("建立Server,PORT为8765。");
int i = 0;
int j = 1;
Socket client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
if(i==1){
break;
}
LineNumberReader wt = new LineNumberReader(new InputStreamReader(
new FileInputStream("D:/file/4813.txt")));
String str = wt.readLine();
while (str != null) {
System.out.println("str=" + str);
out.println(str);
out.flush();
if (str.equals("end")) {
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
str = wt.readLine();
}
// client.close();
i++;
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
// 使用 OutputStreamWriter
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8765);
System.out.println("建立Server,PORT为8765。");
int i = 0;
int j = 1;
Socket client = server.accept();
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
if(i==1){
break;
}
LineNumberReader wt = new LineNumberReader(new InputStreamReader(
new FileInputStream("D:/file/4813.txt")));
String str = wt.readLine();
while (str != null) {
System.out.println("str=" + str);
out.println(str);
out.flush();
if (str.equals("end")) {
break;
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
str = wt.readLine();
}
// client.close();
i++;
}
}
}
本程序可以作为一个SocketServer服务器,读取本地文件,创建一个端口监听,等待客户端连接,然后发送读取的到的文件字符流, 其中"D:/file/4813.txt"为所要读取的文件存放路径
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。