java实现网络通信

这个测试项目很久以前写的,现在发表出来备份一下。

此测试代码主要是实现客户端与服务器端实现通信,使用socket套接字编程实现。

 

 

客户端代码为:

package com.client.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import com.server.test.Server;

public class Client {

	
	public static void main(String[] args)
	{
		Socket s = null;
		BufferedReader br = null;
		PrintWriter pw = null;
		
		try{
			s = new Socket("127.0.0.1",Server.port);
			
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			
			pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())));;
			
			for(int i=0; i<10; i++)
			{
				pw.println("client:" + i);
				pw.flush();
				String str = br.readLine();
				System.out.println(str);
			}
			pw.println("end");
			pw.flush();
		}
		catch(Exception e)
		{
			
		}finally{
			System.out.println("closing...");
			try{
				br.close();
				pw.close();
				s.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}


服务器端代码为:

package com.server.test;

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

public class Server {

	public static int port = 6000;
	
	public static void main(String[] args)
	{
		ServerSocket ss = null;
		Socket s = null;
		BufferedReader br = null;
		
		PrintWriter pw = null;
		
		try{
			ss = new ServerSocket(port);
			s = ss.accept();
			
			//接受客户端发送过来的信息
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			//发送返回信息
			pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
			int num = 0;
			while(true)
			{
				String str = br.readLine();
				if(str.equals("end")) break;
				
				System.out.println("client message is :"+str);
				Thread.sleep(100);
				pw.println("Message received" + num++);
				pw.flush();
			}
			
		}catch(Exception e)
		{
			e.printStackTrace();
			
		}
		finally{
			try{
				br.close();
				pw.close();
				s.close();
				ss.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}


 

posted @ 2013-04-25 09:49  liuwu265  阅读(364)  评论(0编辑  收藏  举报