package myfistsocket;
/*一个作为Server*/
import java.io.*;
import java.net.*;
class MynewServer
{
publicstaticvoid main(String[] args) throws IOException
{
ServerSocket s = new ServerSocket(6666);
System.out.println("服务器端------监听中.....");
Socket socket = s.accept();
System.out.println("开始:" + socket);
GetMessage gm = new GetMessage(socket);
SendMessage sm = new SendMessage(socket);
Thread gt = new Thread(gm);
Thread st = new Thread(sm);
gt.start();
st.start();
}
}
// 接收消息
class GetMessage implements Runnable
{
BufferedReader in;
public GetMessage(Socket socket)
{
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (IOException e)
{
e.printStackTrace();
}
}
publicvoid run()
{
String str = "";
while (true)
{
try
{
str = in.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
if (str.equals("q"))
{
break;
}
System.out.print("客户端回应说:" + str);
}
}
}
// 发送消息
class SendMessage implements Runnable
{
PrintWriter out;
BufferedReader is;
public SendMessage(Socket socket) throws IOException
{
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
is = new BufferedReader(new InputStreamReader(System.in));
}
publicvoid run()
{
String input = new String();
while (true)
{
try
{
input = is.readLine().trim();
}
catch (IOException e)
{
e.printStackTrace();
}
out.println(input);
System.out.print("服务器说:");
out.flush();
}
}
}
java socket一对一聊天 java socket聊天程序
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
websockt一对一聊天java部分
websocket
java websocket -
java socket聊天退出 java socket聊天程序
java socket 之 简单聊天程序 这两天一直在学习java中的socket。前几天学习了一个简单的聊天程序,我尝试着自己写了一个具有可视化界面的版本,用到了简单的多线程,但是服务器端只能接
java socket聊天退出 socket java null import