TCP线程服务器/客户端

时间:2014-02-06 20:54:15

标签: java multithreading sockets networking tcp

TCP服务器

我运行了服务器和客户端,但似乎只有一个线程正在运行。我应该更改端口还是什么?提前谢谢

我运行了服务器和客户端,但似乎只有一个线程正在运行。我应该更改端口还是什么?提前致谢 我运行了服务器和客户端,但似乎只有一个线程正在运行。我应该更改端口还是什么?提前致谢 服务器代码:

package tcpecho;

import java.io.*; 
import java.net.*;


class TCPserver  implements Runnable {
private static String clientMSG;
private static String serverRespond;
private static ServerSocket MySocket=null;
private static Socket client;
private static Socket connectionSocket = null;
private BufferedReader inFromClient = null;
public TCPserver(Socket client){
    TCPserver.client=client;}

public static void main(String[] args)  {


public void socketProcess( )
{



    try {
        clientMSG = inFromClient.readLine();
    } catch (IOException e) {
        System.err.println("Message from client is not readable");
    }

    serverRespond = clientMSG +connectionSocket.getInetAddress()+ '\n';

    try {
        outToClient.writeBytes(serverRespond);
    } catch (IOException e) {
        System.err.println("Message to client is not out");
    } 

    try {
        MySocket.close();
    } catch (IOException e1) {

        System.err.println("Unable to close the socket");
    }

}




} 

}

这是我的客户代码:

package task3;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

class Client {
    public static void main(String argv[]) throws Exception {

        String str;
        String strFromServer;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket client = null;
        // for(int i=0;i<10;i++){
        int port = 6880;
        try {
            client = new Socket("192.168.56.1", port);
        } catch (Exception e) {
            System.err.println("Couldn't connect to the port" + port);
            System.exit(1);
        }

        DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());

        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
        System.out.println("Write a message to the server :");
        str = inFromUser.readLine();

        outToServer.writeBytes(str + '\n');
        strFromServer = inFromServer.readLine();
        System.out.println("Respond from server: " + strFromServer);
        client.close();
    }
}

2 个答案:

答案 0 :(得分:3)

在你这样做之后

connectionSocket = MySocket.accept();

您需要将此connectionSocket实例传递给新线程并在该线程上调用start

此外,将所有connectionSocket处理逻辑移至Thread类的run方法
(此逻辑目前在上面提到的这一行之后的main方法中)。

要实施您自己的Thread,您可以延长Thread或实施Runnable

点击此链接了解更多详情:Java Threads

答案 1 :(得分:0)

只是一个建议,如果您要为所有客户端打开多个线程,您可能需要查看使用非阻塞io的java.nio包。

这将允许您处理更多连接。