socket多线程网络服务器 java

没什么好说的,直接上代码:

首先是服务器,多线程服务器我们可以通过两种方法实现,一种继承Thread,一种实现Runnable接口,以继承为例:

java代码:TCP_server.java

package com.wpf.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP_server extends Thread{
	private Socket socket;
	
	public TCP_server(Socket socket){
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {
			InputStream in  = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			BufferedReader buffered = new BufferedReader(new InputStreamReader(in));
			PrintWriter writer = new PrintWriter(out);

			System.out.println(buffered.readLine());
			writer.println("我是服务器,收到");
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void openServer() throws Exception{
		ServerSocket server = new ServerSocket(9000);
		while(true){
			new TCP_server(server.accept()).start();
		}
	}
}

代码应注意1.文件流的包装

2.write.println(".......");千万不能写成write.write(".........");

3.  ServerSocket server = new ServerSocket(9000);
  while(true){
   new TCP_server(server.accept()).start();
  }的server在循环外面,必须启动该线程,及调用start();

接着,客户端代码:TCP_client

package com.wpf.test;

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

public class TCP_client {
	public static void main(String[] args) throws Exception{
		Socket socket = new Socket("192.168.1.106", 9000);
		OutputStream out = socket.getOutputStream();
		InputStream in = socket.getInputStream();
		BufferedReader buffered = new BufferedReader(new InputStreamReader(in));
		PrintWriter writer = new PrintWriter(out);

		writer.println("client");
		writer.flush();
		System.out.println(buffered.readLine());
	}
}

启动服务:

 StartServer.java

package com.wpf.test;

public class StartServer {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			TCP_server.openServer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值