用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!

用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!,第1张

程序分Server和Client

服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接

一个负责客户端发送的信息(ClientMsgCollectThread 类),

另一个负责通过该Socket发送数据(ServerMsgSendThread )

Serverjava代码如下:

/

创建日期 2009-3-7

TODO 要更改此生成的文件的模板,请转至

窗口 - 首选项 - Java - 代码样式 - 代码模板

/

package faueMutiUser;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintWriter;

import javanetServerSocket;

import javanetSocket;

/

服务器

@author Faue

/

public class Server extends ServerSocket {

private static final int SERVER_PORT = 10000;

/

构造方法,用于实现连接的监听

@throws IOException

/

public Server() throws IOException {

super(SERVER_PORT);

try {

while (true) {

Socket socket = superaccept();

new Thread(new ClientMsgCollectThread(socket), "getAndShow"

+ socketgetPort())start();

new Thread(new ServerMsgSendThread(socket), "send"

+ socketgetPort())start();

}

} catch (IOException e) {

eprintStackTrace();

}

}

public static void main(String[] args) throws IOException {

new Server();

}

/

该类用于创建接收客户端发来的信息并显示的线程

@author Faue

@version 100

/

class ClientMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/

得到Socket的输入流

@param s

@throws IOException

/

public ClientMsgCollectThread(Socket s) throws IOException {

client = s;

in = new BufferedReader(new InputStreamReader(client

getInputStream(), "GBK"));

}

public void run() {

try {

while (!clientisClosed()) {

inputStringBufferdelete(0, inputStringBufferlength());

inputStringBufferappend(inreadLine());

Systemoutprintln(getMsg(inputStringBuffertoString()));

}

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

}

}

/

构造显示的字符串

@param line

@return

/

private String getMsg(String line) {

return clienttoString() + " says:" + line;

}

}

/

该类用于创建发送数据的线程

@author Faue

@version 100

/

class ServerMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/

得到键盘的输入流

@param s

@throws IOException

/

public ServerMsgSendThread(Socket s) throws IOException {

client = s;

out = new PrintWriter(clientgetOutputStream(), true);

keyboardInput = new BufferedReader(new InputStreamReader(Systemin));

}

public void run() {

try {

while (!clientisClosed()) {

outputStringBufferdelete(0, outputStringBufferlength());

outputStringBufferappend(keyboardInputreadLine());

outprintln(outputStringBuffertoString());

}

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

}

}

}

}

客户端:

实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收

/

创建日期 2009-3-7

/

package faueMutiUser;

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintWriter;

import javanetSocket;

/

客户端

@author Faue

/

public class Client {

private Socket mySocket;

/

创建线程的构造方法

@param IP

@throws IOException

/

public Client(String IP) throws IOException {

try {

mySocket = new Socket(IP, 10000);

new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"

+ mySocketgetPort())start();

new Thread(new ClientMsgSendThread(mySocket), "send"

+ mySocketgetPort())start();

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln("ServerIP:" + IP

+ " port:10000 can not be Connected");

}

}

public static void main(String[] args) throws IOException {

try {

new Client(args[0]);

} catch (Exception e) {

Systemoutprintln("输入的IP地址错误");

}

}

/

该类用于创建接收服务端发来的信息并显示的线程

@author Faue

@version 100

/

class ServerMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/

得到Socket的输入流

@param s

@throws IOException

/

public ServerMsgCollectThread(Socket s) throws IOException {

client = s;

in = new BufferedReader(new InputStreamReader(client

getInputStream(), "GBK"));

}

public void run() {

try {

while (!clientisClosed()) {

inputStringBufferdelete(0, inputStringBufferlength());

inputStringBufferappend(inreadLine());

Systemoutprintln(getMsg(inputStringBuffertoString()));

}

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

Systemexit(0);

}

}

/

构造输入字符串

@param line

@return

/

private String getMsg(String line) {

return clienttoString() + " says:" + line;

}

}

/

该类用于创建发送数据的线程

@author Faue

@version 100

/

class ClientMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/

得到键盘的输入流

@param s

@throws IOException

/

public ClientMsgSendThread(Socket s) throws IOException {

client = s;

out = new PrintWriter(clientgetOutputStream(), true);

keyboardInput = new BufferedReader(new InputStreamReader(Systemin));

}

public void run() {

try {

while (!clientisClosed()) {

outputStringBufferdelete(0, outputStringBufferlength());

outputStringBufferappend(keyboardInputreadLine());

outprintln(outputStringBuffertoString());

}

outprintln("--- See you, bye! ---");

} catch (IOException e) {

//eprintStackTrace();

Systemoutprintln(clienttoString() + " is closed!");

Systemexit(0);

}

}

}

}

如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!

vaela

服务器端:

import javaawt;

import javaawtevent;

import javaxswing;

import javaio;

import javanet;

import javautilVector;

public class OneToMoreServer extends JFrame implements ActionListener{

JPanel contentPane;

JLabel jLabel2 = new JLabel();

JTextField jTextField2 = new JTextField("4700");

JButton jButton1 = new JButton();

JLabel jLabel3 = new JLabel();

JTextField jTextField3 = new JTextField();

JButton jButton2 = new JButton();

JScrollPane jScrollPane1 = new JScrollPane();

JTextArea jTextArea1 = new JTextArea();

ServerSocket server = null;

Socket socket = null;BufferedReader instr =null;PrintWriter os=null ;

Vector vector=new Vector();

boolean serverRun=true;

boolean clientRun=true;

//Construct the frame

public OneToMoreServer() {

jbInit();

}

class MyThread extends Thread{//该线程负责接收数据

Socket socketI=null;

BufferedReader br=null;

public MyThread(Socket socket)

{

socketI=socket;

}

public void run(){

try{

while(clientRun){

thissleep(100);

br= new BufferedReader(new InputStreamReader(socketIgetInputStream()));

if(brready()){ //检查是否有数据

jTextArea1append("接收到来自客户端("+socketIgetInetAddress()toString()+")的消息: "+brreadLine()+"\n");

}

}

}catch(Exception ex){JOptionPaneshowMessageDialog(null,extoString());}

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==jButton1){

int port=IntegerparseInt(jTextField2getText()trim());

//监听指定端口

try

{

server = new ServerSocket(port);

new Thread(new ListenClient())start();

}

catch(IOException ex)

{

JOptionPaneshowMessageDialog(null,extoString());

}

}

if(egetSource()==jButton2){

String msg=jTextField3getText()trim();

if(msglength()!=0)

sendData("hello");

}

}

//该线程负责监听指定端口

class ListenClient implements Runnable

{

public void run()

{

try{

if(jButton1getText()trim()equals("侦听")){

jButton1setText("正在侦听");

while(serverRun)

{

Socket socketI=serveraccept();//有客户端连入时建立一个线程监听客户端发送的消息

vectoradd(socketI);

jButton1setText("正在聊天");

jTextArea1append("客户端"+socketIgetInetAddress()toString()+"已经连接到服务器\n");

MyThread t=new MyThread(socketI);

tstart();

}

}

}catch(Exception ex){

JOptionPaneshowMessageDialog(null,extoString());

}

}

}

private void sendData(String s){//发送数据

try{

for(int i=0;i<vectorsize();i++)

{

//怎么广播

//向每个客户端发送一条消息

Socket socket=(Socket)vectorget(i);

os= new PrintWriter(socketgetOutputStream());

osprintln(s);

osflush();

}

}catch(Exception ex){

}

}

private void jbInit() {

contentPane = (JPanel) thisgetContentPane();

contentPanesetLayout(null);

thissetSize(new Dimension(540, 340));

thissetTitle("服务器");

jLabel2setBounds(new Rectangle(22, 27, 72, 28));

jLabel2setText("端口号");

jLabel2setFont(new javaawtFont("宋体", 0, 14));

jTextField2setBounds(new Rectangle(113, 27, 315, 24));

jButton1setBounds(new Rectangle(440, 28, 73, 25));

jButton1setFont(new javaawtFont("Dialog", 0, 14));

jButton1setBorder(BorderFactorycreateEtchedBorder());

jButton1setActionCommand("jButton1");

jButton1setText("侦听");

jLabel3setBounds(new Rectangle(23, 57, 87, 28));

jLabel3setText("请输入信息");

jLabel3setFont(new javaawtFont("宋体", 0, 14));

jTextField3setBounds(new Rectangle(114, 60, 314, 24));

jTextField3setText("");

jButton2setText("广播");

jButton2setActionCommand("jButton1");

jButton2setBorder(BorderFactorycreateEtchedBorder());

jButton2setFont(new javaawtFont("Dialog", 0, 14));

jButton2setBounds(new Rectangle(440, 58, 73, 25));

jScrollPane1setBounds(new Rectangle(23, 92, 493, 189));

contentPaneadd(jTextField2, null);

contentPaneadd(jButton1, null);

contentPaneadd(jLabel3, null);

contentPaneadd(jTextField3, null);

contentPaneadd(jButton2, null);

contentPaneadd(jScrollPane1, null);

contentPaneadd(jLabel2, null);

jScrollPane1getViewport()add(jTextArea1, null);

jButton1addActionListener(this);

jButton2addActionListener(this);

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

try{

socketclose();

instrclose();

Systemexit(0);

}catch(Exception ex){

//JOptionPaneshowMessageDialog(null,extoString());

}

}

});

}

public static void main(String arg[]){

JFramesetDefaultLookAndFeelDecorated(true);

OneToMoreServer frm=new OneToMoreServer();

frmsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

frmsetVisible(true);

}

}

客户端

import javaawt;

import javaawtevent;

import javaxswing;

import javaio;

import javanet;

public class Client extends JFrame implements ActionListener{

JPanel contentPane;

JLabel jLabel1 = new JLabel();

JTextField jTextField1 = new JTextField("127001");

JLabel jLabel2 = new JLabel();

JTextField jTextField2 = new JTextField("4700");

JButton jButton1 = new JButton();

JLabel jLabel3 = new JLabel();

JTextField jTextField3 = new JTextField();

JButton jButton2 = new JButton();

JScrollPane jScrollPane1 = new JScrollPane();

JTextArea jTextArea1 = new JTextArea();

BufferedReader instr =null;

Socket socket = null;

PrintWriter os=null;

public Client() {

jbInit();

}

class MyThread extends Thread{

public void run(){

try{

os=new PrintWriter(socketgetOutputStream());

instr=new BufferedReader(new InputStreamReader(socketgetInputStream()));

while(true)

{

thissleep(100);

if(instrready())

{

jTextArea1append("接收到来自服务器的消息: "+instrreadLine()+"\n");

}

}

}catch(Exception ex){

JOptionPaneshowMessageDialog(null,extoString());

}

}

}

public void actionPerformed(ActionEvent e){

if(egetSource()==jButton1){

String ip=jTextField3getText()trim();

int port=IntegerparseInt(jTextField2getText()trim());

connectServer(ip,port);

}

if(egetSource()==jButton2){

String s=thisjTextField3getText()trim();

sendData(s);

}

}

private void connectServer(String ip,int port){//连接

try{

if(jButton1getText()trim()equals("连接")){

jButton1setText("连接服务器");

socket=new Socket(ip,port);

jButton1setText("正在聊天");

MyThread t=new MyThread();

tstart();

}

}catch(Exception ex){

JOptionPaneshowMessageDialog(this,extoString());

}

}

private void sendData(String s){//发送数据

try{

os = new PrintWriter(socketgetOutputStream());

osprintln(s);

osflush();

thisjTextArea1append("向服务器发送消息:"+s+"\n");

}catch(Exception ex){

JOptionPaneshowMessageDialog(this,extoString());

}

}

private void jbInit() {

contentPane = (JPanel) thisgetContentPane();

jLabel1setFont(new javaawtFont("宋体", 0, 14));

jLabel1setText("服务器名称");

jLabel1setBounds(new Rectangle(20, 22, 87, 28));

contentPanesetLayout(null);

thissetSize(new Dimension(540, 340));

thissetTitle("客户端");

jTextField1setBounds(new Rectangle(114, 26, 108, 24));

jLabel2setBounds(new Rectangle(250, 25, 72, 28));

jLabel2setText("端口号");

jLabel2setFont(new javaawtFont("宋体", 0, 14));

jTextField2setBounds(new Rectangle(320, 27, 108, 24));

jButton1setBounds(new Rectangle(440, 28, 73, 25));

jButton1setFont(new javaawtFont("Dialog", 0, 14));

jButton1setBorder(BorderFactorycreateEtchedBorder());

jButton1setActionCommand("jButton1");

jButton1setText("连接");

jLabel3setBounds(new Rectangle(23, 57, 87, 28));

jLabel3setText("请输入信息");

jLabel3setFont(new javaawtFont("宋体", 0, 14));

jTextField3setBounds(new Rectangle(114, 60, 314, 24));

jButton2setText("发送");

jButton2setActionCommand("jButton1");

jButton2setBorder(BorderFactorycreateEtchedBorder());

jButton2setFont(new javaawtFont("Dialog", 0, 14));

jButton2setBounds(new Rectangle(440, 58, 73, 25));

jScrollPane1setBounds(new Rectangle(23, 92, 493, 189));

contentPaneadd(jLabel1, null);

contentPaneadd(jTextField1, null);

contentPaneadd(jLabel2, null);

contentPaneadd(jTextField2, null);

contentPaneadd(jButton1, null);

contentPaneadd(jLabel3, null);

contentPaneadd(jTextField3, null);

contentPaneadd(jButton2, null);

contentPaneadd(jScrollPane1, null);

jScrollPane1getViewport()add(jTextArea1, null);

jButton1addActionListener(this);

jButton2addActionListener(this);

thisaddWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

try{

socketclose();instrclose();osclose();Systemexit(0);

}catch(Exception ex){

JOptionPaneshowMessageDialog(null,extoString());

}

}

});

}

public static void main(String arg[]){

JFramesetDefaultLookAndFeelDecorated(true);

Client frm=new Client();

frmsetVisible(true);

}

}

import javaawtColor;

import javaawtDimension;

import javaawtFont;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaawteventKeyEvent;

import javaawteventKeyListener;

import javaioIOException;

import javanetDatagramPacket;

import javanetDatagramSocket;

import javanetInetAddress;

import javaxswingJButton;

import javaxswingJFrame;

import javaxswingJPanel;

import javaxswingJScrollPane;

import javaxswingJSplitPane;

import javaxswingJTextArea;

public class ChatFrame extends JPanel{

private static final long serialVersionUID = 1L;

private int width=450,height=450;

boolean flag;

int port = 10086;

String address = "1921683352";

// int port = 2425;

DatagramSocket send;

DatagramSocket receive;

UDP_Send udpSend;

JTextArea showTextArea;

JTextArea inputTextArea;

JPanel rightPanel;

JScrollPane scrollPane1;

JScrollPane scrollPane2;

JSplitPane splitPane1;

JSplitPane splitPane2;

JButton sendButton;

JButton closeButton;

JPanel buttonpane;

public ChatFrame() throws Exception {

super(null, true);

send = new DatagramSocket();

receive = new DatagramSocket(port);

udpSend =new UDP_Send(send,port);

showTextArea = new JTextArea();

showTextAreasetLineWrap(true);

showTextAreasetEditable(false);

showTextAreasetForeground(new Color(0xf90033));

scrollPane1 = new JScrollPane(showTextArea);

inputTextArea = new JTextArea();

inputTextAreasetLineWrap(true);

scrollPane2 = new JScrollPane(inputTextArea);

rightPanel = new JPanel();

rightPanelsetBackground(new Color(0x0099ff));

splitPane1 = new JSplitPane(JSplitPaneVERTICAL_SPLIT,true,scrollPane1,scrollPane2);

splitPane2 = new JSplitPane(JSplitPaneHORIZONTAL_SPLIT,true,splitPane1,rightPanel);

inputTextAreaaddKeyListener(new KeyListener() {

@Override

public void keyTyped(KeyEvent e) {}

@Override

public void keyReleased(KeyEvent e) {}

@Override

public void keyPressed(KeyEvent e) {

switch (egetKeyCode()) {

case KeyEventVK_ENTER:

udpSendsend(port);

inputTextAreasetText("");

break;

default:

break;

}

}

});

sendButton = new JButton("发送");

sendButtonaddActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

udpSendsend(port);

inputTextAreasetText("");

}

});

closeButton = new JButton("关闭");

closeButtonaddActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

Systemexit(0);

}

});

buttonpane = new JPanel();

buttonpaneadd(closeButton);

buttonpaneadd(sendButton);

splitPane1setBounds(0, 0, width, height-32);

splitPane1setDividerLocation(08);

splitPane2setBounds(0, 0, width, height-32);

splitPane2setDividerLocation(08);

buttonpanesetBounds(width-250, height-32, 140, 32);

thisadd(splitPane2);

thisadd(buttonpane);

thissetPreferredSize(new Dimension(width,height));

new Thread(new UDP_Receive(receive))start();

}

public static void main(String[] args) throws Exception {

JFrame frame = new JFrame();

framesetContentPane(new ChatFrame());

framepack();

framesetResizable(false);

framesetLocationRelativeTo(null);

framesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

framesetVisible(true);

}

class UDP_Send{

DatagramSocket datagramSocket;

int port;

String text;

public UDP_Send(DatagramSocket datagramSocket,int port) {

thisdatagramSocket = datagramSocket;

thisport = port;

}

public void send(int port) {

try {

text = new String(inputTextAreagetText()getBytes(), "utf-8");

byte buffered[] = textgetBytes();

DatagramPacket database = new DatagramPacket(buffered,

bufferedlength, InetAddressgetByName(address),port) ;

showTextAreasetFont(new Font("微软雅黑", FontCENTER_BASELINE, 24));

showTextAreaappend("本机"+":\n");

showTextAreasetFont(new Font("仿宋", FontCENTER_BASELINE, 16));

showTextAreaappend(" "+text+"\n");

datagramSocketsend(database);

} catch (IOException e) {

eprintStackTrace();

}

}

}

class UDP_Receive implements Runnable {

DatagramSocket datagramSocket;

public UDP_Receive(DatagramSocket datagramSocket) {

thisdatagramSocket = datagramSocket;

}

@Override

public void run() {

try {

byte buff[] = new byte[4096];

DatagramPacket database = new DatagramPacket(buff, bufflength);

while (true) {

datagramSocketreceive(database);

String text = new String(databasegetData(), 0,databasegetLength(),"utf-8");

showTextAreasetFont(new Font("微软雅黑", FontCENTER_BASELINE, 24));

showTextAreaappend(databasegetAddress()+":\n");

showTextAreasetFont(new Font("仿宋", FontCENTER_BASELINE, 16));

showTextAreaappend(" "+text+"\n");

}

} catch (IOException e) {

eprintStackTrace();

}

}

}

}

在客户端退出之后,会出现socket连接中断,此时是会抛出异常,在抛出异常时打印中断的客户端即可。

1 while(Binputread()()!= -1) 这种方法能判断出客户端输入是否为空,客户端断开能跳出死循环,但是得到的数据却从第二个开始了,所以这方法不适宜。

2 在死循环中加入以下代码:

try {

socketsendUrgentData(0);

} catch (IOException e) {

done= false; //如果抛出了异常,那么就是断开连接了 跳出无限循环

}

服务端:

//读取从客户端传过来的数据并发送到客户端

while((str=brreadLine())!=null)

{

pwprint(str);

pwflush();

Systemoutprint(str);

}

pwprint(str);这一行要改成 pwprintln(str); 因为你都是用readLine去读数据,不用println他不会认为你的行已结束了

客户端:

你根本没有从服务端读数据的代码,怎么能够读得到呢?

把代码: pwprint(str1); 也改成 pwprintln(str1);

在 pwflush();

之后加入

String returnStr = brreadLine();

Systemoutprintln("服务器返回:" + returnStr);

就可以了

import javanet;

import javaio;

public class Server {

public static void main(String[] args) throws IOException {

String s = "";//用stringbuffer试试

String s1 = "";

ServerSocket server = new ServerSocket(60000);

Systemoutprintln("可以开始通信");

try {

Socket socket = serveraccept();

Systemoutprintln(socket);

InputStream is = socketgetInputStream();

OutputStream out = socketgetOutputStream();

BufferedReader bfr = new BufferedReader(new InputStreamReader(is));

PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));

BufferedReader br = new BufferedReader(new InputStreamReader(Systemin));

while (true) {

s = bfrreadLine();

Systemoutprintln("客户端对我说:" + s);//读取客户端信息并输出

if("bye"equals(s)) {

pwprintln("bye");

pwflush();

break;

}

s1 = brreadLine();

pwprintln(s1);

pwflush();

Systemoutprintln("我对客户端说:" + s1);

}

socketclose();

} catch (IOException e) {

eprintStackTrace();

}

serverclose();

}

class Reader extends Thread {

public void run() {

while (true) {

}

}

}

}

import javanet;

import javaio;

public class Talk {

static InputStream is = null;

static OutputStream out;

static BufferedReader bfr;

static PrintWriter pw;

static BufferedReader pin;

public static void main(String[] args) throws IOException {

Socket socket = new Socket(InetAddressgetByName("localhost"), 60000);

Systemoutprintln(socket);

try {

is = socketgetInputStream();

out = socketgetOutputStream();

bfr = new BufferedReader(new InputStreamReader(is));

pw = new PrintWriter(new OutputStreamWriter(out));

pin = new BufferedReader(new InputStreamReader(Systemin));

new Controlaa()start();

while (true) {

String s1 = bfrreadLine();

Systemoutprintln("服务器对我说:" + s1);//读取服务器端发送的信息

if (s1equals("bye")) {

break;

}

}

socketclose();

} catch (IOException e) {

eprintStackTrace();

}

}

static class Controlaa extends Thread {

@Override

public void run() {

while (true) {

String s = "";

try {

s = pinreadLine();

} catch (IOException ex) {

exprintStackTrace();

}

Systemoutprintln("我对服务器说:" + s);

pwprintln(s);

pwflush();

}

}

}

}

简单搞了下,读取控制台输入和读取socket都是阻塞操作

服务器端代码:

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintStream;

import javanetServerSocket;

import javanetSocket;

/

Socket通讯服务器端

@author 米强

/

public class ServerMain {

public ServerMain() {

try {

// 构造服务器ServerSocket对象,参数为服务器端开放的端口号

ServerSocket ss = new ServerSocket(30102);

Systemoutprintln("服务器准备就绪!");

// 死循环可以使服务器持续处于接收客户端状态

while(true){

// 该方法使程序阻塞,等待客户端的链接,当监听到客户端的链接,创建一个Socket对象与客户端单独会话

Socket s = ssaccept();

// 为了不影响服务器监听其它客户端,这里开启了一个线程,由线程处理与这个客户端的会话

new ServerThread(s)start();

}

} catch (IOException e) {

eprintStackTrace();

}

}

public static void main(String[] args) {

new ServerMain();

}

}

/

服务器端与客户端会话的线程

/

class ServerThread extends Thread {

private Socket s = null;

private BufferedReader read = null;

private PrintStream print = null;

public ServerThread(Socket s) {

thiss = s;

try {

// 从Socket中获取输入流和输出流,由于我们只做一个简单的字符串通讯,所以采用BufferedRead和PrintStream来封装输入、输出流

read = new BufferedReader(new InputStreamReader(sgetInputStream()));

print = new PrintStream(sgetOutputStream());

} catch (IOException e) {

eprintStackTrace();

}

}

/

线程的运行run方法

/

public void run() {

try {

String message = null;

// 这里循环可以使服务器持续的接收客户端信息。readreadLine()通过输入流读取一段字符串,赋值给message变量,如果message字符串不为“exit”则循环,否则结束循环

while (!(message = readreadLine())equals("exit")){

// 将字符串前面添加“返回:”,再发回客户端

printprintln("返回:" + message);

}

} catch (IOException e) {

} finally {

// 在 finally 代码块中无论如何都会执行下面代码:

try {

// 如果没有关闭Socket

if(!sisClosed()){

// 关闭Socket链接

sclose();

}

} catch (IOException e1) {

e1printStackTrace();

}

}

}

}

客户端代码:

import javaioBufferedReader;

import javaioIOException;

import javaioInputStreamReader;

import javaioPrintStream;

import javanetSocket;

import javanetUnknownHostException;

import javautilScanner;

/

Socket通讯客户端

@author 米强

/

public class ClientMain {

public ClientMain() {

try {

// 构造与服务器通讯的Socket对象,参数为服务器IP地址(String)和端口号(int),端口号需要和服务器端开放的端口号对应

Socket s = new Socket("1921681100", 30102);

// 启动一个线程与服务器通讯,并把链接服务器的Socket对象传递过去

new LinkThread(s)start();

} catch (UnknownHostException e) {

eprintStackTrace();

} catch (IOException e) {

eprintStackTrace();

}

}

public static void main(String[] args) {

new ClientMain();

}

}

/

与服务器通讯的线程

/

class LinkThread extends Thread {

private Socket s = null;

// 输出流

private PrintStream out = null;

// 缓冲输入流

private BufferedReader in = null;

// 录入文字的Scanner对象

private Scanner scanner = null;

public LinkThread(Socket s) {

// 将Socket对象实例保存在全局变量中,因为run方法中我们还要用它断开链接

thiss = s;

try {

// 从Socket中获取输入流和输出流,由于我们只做一个简单的字符串通讯,所以采用BufferedRead和PrintStream来封装输入、输出流

out = new PrintStream(sgetOutputStream());

in = new BufferedReader(new InputStreamReader(sgetInputStream()));

} catch (UnknownHostException e) {

eprintStackTrace();

} catch (IOException e) {

eprintStackTrace();

}

}

/

线程的运行run方法

/

public void run() {

// 构造Scanner对象

scanner = new Scanner(Systemin);

Systemoutprintln("提示:如果要结束本次会话,请输入“exit”指令!");

try {

// 死循环可以使客户端不断的向服务器发送信息,不用担心循环无法结束,后面的return语句可以结束整个线程。

while(true){

// 提示用户输入文字

Systemoutprint("请输入:");

// 将用户输入的字符串保存在message变量中

String message = scannernextLine();

// 通过输出流发送字符串

outprintln(message);

// 清空缓冲,强制输出

outflush();

// 获取服务器返回的字符串

String str = inreadLine();

// 如果返回的字符串存在

if(str != null){

// 显示在控制台

Systemoutprintln(str);

}else{

// 提示会话结束,并结束线程

Systemoutprintln("本次会话结束!");

return;

}

}

} catch (IOException e) {

eprintStackTrace();

} finally {

// 在 finally 代码块中无论如何都会执行下面代码:

try {

// 如果没有关闭Socket

if(!sisClosed()){

// 关闭Socket链接

sclose();

}

} catch (IOException e1) {

e1printStackTrace();

}

}

}

}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情