【Java学习笔记】TCP客户端/服务器端

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

客户端:

import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.IOException;
public class TcpClient {
    public static void main(String[] args) throws IOException {
        try {
            byte a[] = { 127,0,0,1 };
            InetAddress address = InetAddress.getByAddress(a);
            Socket socket = new Socket(address,9876);
            OutputStream os = socket.getOutputStream();
            PrintWriter out = new PrintWriter(os,true);
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            String line;
            line = "A line sent by the client";
            out.println(line);
            line = in.readLine();
            System.out.println("client got: " + line);
            out.close();
            in.close();
            socket.close();
        } catch (UnknownHostException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

服务器端:

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
public class TcpServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9876);
            Socket socket = serverSocket.accept();
/*和Client一样了*/
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            OutputStream os = socket.getOutputStream();
            PrintWriter out = new PrintWriter(os,true);
            String line;
            while((line = in.readLine()) != null) {
                 System.out.println("server got: " + line);
                 line = "A line sent by the server";
                 out.println(line);
            }
            out.close();
            in.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            System.out.println(e);
            System.exit(1);
        }
    }
}

 

作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值