首页 > 代码库 > Java网络编程(tcp在服务器上应用多线程)
Java网络编程(tcp在服务器上应用多线程)
package org.tcp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class EchoThread implements Runnable {
private Socket client = null;
public EchoThread(Socket client){
this.client = client;
}
@Override
public void run() {
// TODO 自动生成的方法存根
PrintStream out = null;
BufferedReader buf = null;
try{
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream(client.getOutputStream());
boolean flag = true;
while(flag){
String str = buf.readLine();
if(str == null||"".equals(str)){
flag = false;
}else{
if("bye".equals(str)){
flag = false;
}else{
out.println("ECHO:"+str);
}
}
}
out.close();
client.close();
}catch(Exception e){
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class EchoThread implements Runnable {
private Socket client = null;
public EchoThread(Socket client){
this.client = client;
}
@Override
public void run() {
// TODO 自动生成的方法存根
PrintStream out = null;
BufferedReader buf = null;
try{
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream(client.getOutputStream());
boolean flag = true;
while(flag){
String str = buf.readLine();
if(str == null||"".equals(str)){
flag = false;
}else{
if("bye".equals(str)){
flag = false;
}else{
out.println("ECHO:"+str);
}
}
}
out.close();
client.close();
}catch(Exception e){
}
}
}
package org.tcp;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoThreadSocket {
public static void main(String[] args) throws Exception{
ServerSocket server = null;
Socket client = null;
server = new ServerSocket(8888);
boolean f = true;
while(f){
System.out.println("服务器运行,等待客户端链接。");
client = server.accept();
new Thread(new EchoThread(client)).start();
}
server.close();
}
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。