用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

java socket 监听 服务端和客户端

2015-01-07 作者: java源代码大全举报

[java]代码库

package cn.outofmemory.socket.example;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class App {
    public static void main(String[] args) throws IOException {
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 19999;
        ServerSocket server = new ServerSocket(port);
        System.out.println("server waits client");
        Socket client = server.accept();
        System.out.println("client comes. please write to client");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

        BufferedReader consoleRdr = new BufferedReader(new InputStreamReader(System.in));
        String line;
        do {
            line = consoleRdr.readLine();
            if ("quit".equals(line)) {
                break;
            }

            bw.write(line);
            bw.write("\r\n");
            bw.flush();
        } while (true);

        bw.close();
        server.close();

        System.out.println("bye");
    }
}
//源代码片段来自云代码http://yuncode.net



package cn.outofmemory.socket.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

    public static void main(String[] args) throws UnknownHostException, IOException {
        final int PORT = 19999;
        Socket client = new Socket("localhost", PORT);

        BufferedReader rdr = new BufferedReader(new InputStreamReader(client.getInputStream()));
        do {
            String line = rdr.readLine();
            System.out.print("server said:");
            System.out.println(line);
        } while (true);
    }
}
//源代码片段来自云代码http://yuncode.net
			
			


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...