线程与网络编程的经典习题

[size=small][size=medium][size=large][color=blue]


1:服务器无限向客户端发送你好javaimport java.net.*;
import java.io.*;

public class Server2 {
private ServerSocket server;

public Server2() throws Exception {
server = new ServerSocket(8802);//在8802端口监听
}
//启动线程
public void init() throws Exception {
while (true) {
Socket socket= server.accept();
OutputStream ous = client.getOutputStream();
Thread2 t = new Thread2 (socket);
t.start();
}
}

public static void main(String[] args) throws Exception {
new Server2().init();
}
}
import java.net.*;
import java.io.*;
public class Thread2 extends Thread{
private Socket socket;
public Thread2 (Socket socket) {
super();
this.socket = socket;
}

public void run(){
try{
OutputStream ous=socket.getOutputStream();
while(true){
ous.write("java 你好".getBytes());
}
}catch(Exception e){}
}
}


2:通过命令行实现多客户群聊
import java.net.*;
import java.io.*;
import java.util.*;

public class Server1 {
private ArrayList<Socket> list = new ArrayList();

private ServerSocket server = new ServerSocket(9999);//服务器在9999端口监听

public Server1() throws Exception {
this.init();
}
//执行线程
public void init() throws Exception {
while (true) {
Socket socket = server.accept();
list.add(socket);
Thread t = new Thread(new Run(this, socket));
t.start();
}
}
//将从客户端接收到信息发送给每一个客户
public void sendAll(String msg) throws Exception {
for (int i = 0; i < list.size(); i++) {
OutputStream os = list.get(i).getOutputStream();
os.write(msg.getBytes());
}
}

public void setList(ArrayList<Socket> list) {
this.list = list;
}
}


import java.net.*;
import java.io.*;
import java.util.*;

public class Run implements Runnable {
private Server1 s1;
private Socket currentsocket;

public Run(Server1 s1, Socket currentsocket) {
this.s1 = s1;
this.currentsocket = currentsocket;
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(currentsocket
.getInputStream()));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str + "\n");
s1.sendAll(str);//调用sendAll方法将从客户端接收的消息发送给每一个客户
System.out.println();
}
} catch (Exception e) {
}
}

}


public class Test {
public static void main(String[] args)throws Exception {
Server1 s = new Server1();

}

}[/color][/size][/size][/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值