编写程序实现网页访问服务器,java 编写网络客户/服务器程序,实现如下功能: (1)设计服务器程序,运行时等待客户端连接; (2)客户...

满意答案

dcebd7a0de6265b6ccae5ead692f1eab.png

cx110112113

推荐于 2017.12.15

dcebd7a0de6265b6ccae5ead692f1eab.png

采纳率:58%    等级:12

已帮助:6312人

Server:

package s;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

public class Server {

public static void main(String[] args) throws IOException {

ServerSocket server = new ServerSocket(10001);

while (true) {

Socket socket = server.accept();

System.out.println("a socket in");

new UpderDeal(socket).start();

}

}

}

class UpderDeal extends Thread {

private Socket s = null;

public UpderDeal(Socket s) {

this.s = s;

}

public void run() {

byte[] b = new byte[1024];

String msg = null;

int len = 0;

try {

while (true) {

len = s.getInputStream().read(b);

msg = new String(b, 0, len);

msg = msg.toUpperCase();

s.getOutputStream().write(msg.getBytes());

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

Client:

package c;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Scanner;

public class Client {

public static void main(String[] args) throws UnknownHostException,

IOException {

Socket socket = new Socket("localhost", 10001);

OutputStream out = socket.getOutputStream();

InputStream in = socket.getInputStream();

String msg = null;

Scanner sc = new Scanner(System.in);

new Recieve(in).start();

while (true) {

msg = sc.next();

if (msg.equals("exit")) {

break;

}

System.out.println("发出的信息:" + msg);

out.write(msg.getBytes());

}

}

}

class Recieve extends Thread {

private InputStream in = null;

public Recieve(InputStream in) {

this.in = in;

}

public void run() {

byte[] b = new byte[1024];

int len = 0;

while (true) {

try {

len = in.read(b);

System.out.println("收到的信息为:" + new String(b, 0, len));

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

希望可以帮到你,还有一种异步用SocketChannel的,我也怎么用过,可以网上参考一下。

00分享举报

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值