码迷,mamicode.com
首页 > 编程语言 > 详细

Java TCP 程序

时间:2015-07-25 21:25:53      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

服务器采用BIO模式,每一个线程处理一个连接。问题出现在,如果使用BufferedReader去读取字符流,如果没有换行符的话,那么就会导致线程阻塞。

import java.io.*;
import java.net.Socket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.Scanner;

class ServerSocketTest {
	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(6000);
			System.out.println("Server running, waitting for client to login ...");
			Socket s = ss.accept();
			
			OutputStream os = s.getOutputStream();
			InputStream is = s.getInputStream();
			os.write("Hello Wellcome\n".getBytes());
			os.flush();
			
	
			/*
			byte[] buf = new byte[1024];
			int len = is.read(buf);
			System.out.println(new String(buf,0,len));*/
			
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while((line = br.readLine()) != null){
				System.out.println(line);
			}
			
			os.close();
			is.close();
			s.close();
			ss.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 客户端程序。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketTest {
	public static void main(String[] args){
		try {
			System.out.println(InetAddress.getLocalHost());
			Socket s = new Socket(InetAddress.getLocalHost(), 6000);
			
			OutputStream os = s.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			pw.write("username:fangying;password:123\n");
			pw.flush();
			
			InputStream is = s.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println("client get :" + line);
			}

			br.close();
			is.close();
			pw.close();
			os.close();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

Java TCP 程序

标签:

原文地址:http://www.cnblogs.com/fangying7/p/4676484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!