欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Socket 编程 博客分类: java基础 SocketJavathread 

程序员文章站 2024-02-13 18:01:58
...
Server.java
package org.iteye.bbjava.socket.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.iteye.bbjava.socket.socketthread.SocketThread;

public class Server {
	private ServerSocket ss;

	public Server() throws IOException {
		ss = new ServerSocket(3000);
	}

	public void sendInfo() {

	}

	public void receiveInfo() throws IOException {
		Socket s =null;
		while(true){
		s = ss.accept();
		System.out.println("ok");
		new SocketThread(s).start();
		}
		
	}
	
	public static void main(String []args){
		try {
			new Server().receiveInfo();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


SocketThread.java
package org.iteye.bbjava.socket.socketthread;

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

public class SocketThread extends Thread {

	private Socket s = null;

	public SocketThread(Socket s) {
		this.s = s;

	}

	@Override
	public void run() {
		InputStream is = null;
		try {
			is = s.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String str = "";
		while (true) {
			try {
				str = br.readLine();
				System.out.println(str);
			} catch (IOException e) {
				e.printStackTrace();
				break;
			} 
			if (str.equals("exit")) {
				break;
			}
		}
		try {
			s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

}


Client.java
package org.iteye.bbjava.socket.client;

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

public class Client {
	private Socket s = null;

	public Client() throws Exception {
		s = new Socket("localhost", 3000);
	}

	public void send() throws IOException {
		InputStream is = null;
		OutputStream os = null;

		try {
			os = s.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));    


		String infoStr = "";
		while (true) {
			try {
				infoStr = br.readLine();
				out.println(infoStr);
				//System.out.println(infoStr);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (infoStr.equals("exit"))
				break;
		}
		s.close();
	}

	public static void main(String[] args) {
		try {
			new Client().send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}