📄 connectthread.java
字号:
//********************************************************************
//
// ConnectThread.java
//
// ConnectThread 类,负责客户端的连接和数据发送,接收
//
//********************************************************************
import java.net.*;
import java.io.*;
import Server;
public class ConnectThread extends Thread
{
BufferedReader m_input;
BufferedWriter m_output;
String m_name;
int m_id;
Socket m_socket;
Server main;
boolean quit;
public ConnectThread()
{
}
public ConnectThread(Server _main,byte _id,Socket socket)
{
main = _main;
m_socket = socket;
m_id = _id;
m_name = new String("Noname");
quit = false;
try
{
m_input = new BufferedReader( new InputStreamReader( socket.getInputStream()) );
m_output = new BufferedWriter ( new OutputStreamWriter( socket.getOutputStream()));
}
catch(IOException e)
{
System.out.println ("Error at init stream "+e);
System.out.print("Disconnect with ");
System.out.println(this.m_name);
main.m_connect[m_id] = null;
this.stop();
}
System.out.println("connect init");
}
public void Send(int type,String obj,String str)
{
String msg = main.WriteMsg(type,obj,str);
Send(msg);
}
public void Send(String str)
{
str+="\n";
try
{
m_output.write ( str);
m_output.flush();
}
catch(IOException e)
{
System.out.println("Error at sending : "+e);
System.out.println (" Disconnect with server");
main.Disconnect(this);
return;
}
System.out.println("Sended data");
}
//丛输入流读一个字节
public String ReceiveChar()
{
char bytes[];
int num;
try
{
bytes= new char[1];
num = m_input.read(bytes,0,1);
if (num>0)
{
System.out.println( (new String(bytes) ) );
return (new String( bytes ));
}
else
{
return null;
}
}
catch(IOException e)
{
main.Disconnect(this);
}
return null;
}
//从输入流读一行
public String Receive()
{
String buf = null;
try
{
buf = m_input.readLine();
}
catch(IOException e)
{
System.out.print(" Error on read from ");
System.out.println(this.m_name);
System.out.print(" Disconnect with ");
System.out.println(m_name);
main.Disconnect(this);
}
return buf;
}
public void run()
{
String str = new String();
while(!quit)
{
str = Receive();
if (str != null ) main.DealInput(str,this);
}
try
{
m_input.close();
m_output.close();
m_socket.close();
}
catch(IOException e)
{
System.out.println("Error at closing disconnected socket : " +e );
}
this.stop();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -