我正在用Java编写聊天程序。我似乎无法发送消息。我的ClientConnectionHandler
处理每个客户端的实例
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
public class ClientConnectionHandler extends Thread {
private Socket socket;
String username;
private UUID id; //= UUID.randomUUID();
BufferedReader reader;
PrintWriter writer;
private final HashMap<UUID, ClientConnectionHandler> clients = new HashMap<>();
volatile boolean messageLoop = true;
ServerGUI serverGUI;
public ClientConnectionHandler(Socket socket){
this.socket = socket;
try{
this.socket.setSoTimeout(1000);
}
catch (SocketException e) {
System.out.println(e);
}
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
}
catch (Exception e){
e.printStackTrace();
}
}
public void run(){
if (socket != null && reader != null) {
addToClients();
try {
String messageInput;
while (messageLoop){
try{
messageInput = reader.readLine();
sendMessage(messageInput);
}
catch(SocketTimeoutException ste){
//Thread.yield();
}
}
}
catch (IOException e){
e.printStackTrace();
}
finally {
removeFromClients();
try {
reader.close();
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
else {
System.out.println("Socket connection and BufferedReader are closed");
}
}
private void sendMessage(String msg){
for (ClientConnectionHandler cchandler : clients.values()){
try {
//if (!clientconn.id.equals(this.id)) {
cchandler.writer.write(msg+"\n");
cchandler.writer.flush();
//}
}
catch (Exception e){
System.err.println("Unable to write to client");
clients.remove(cchandler.id);
}
}
}
}
这是我的Client
班级
public class Client {
private Socket clientSocket;
private String username;
private static int port = 7777;
BufferedReader inReader;
PrintWriter outWriter;
private SimpleDateFormat sdf;
ClientGUI clientGUI;
ServerGUI serverGUI;
private Login login;
public Client(String username, int port){
this.username = username;
this.port = port;
sdf = new SimpleDateFormat("dd.MM.yyyy 'at' hh:mm:ss a");
}
/**
* Connects the client to the Server
*/
public void connectClient(){
try{
clientSocket = new Socket("127.0.0.1", port);
Thread thread = new Thread(new ClientConnectionHandler(clientSocket));
thread.start();
String connected = sdf.format(new Date())+"\n"+username+" just connected \n";
System.out.println(connected);
}
catch(Exception e){
System.out.println(sdf.format(new Date())+"\n"+username+" did not connect to server "+e+"\n");
}
}
/**
* Disconnects the Client from the Server
*/
void disconnectClient(){
try{
clientSocket.close();
System.out.println(username+" disconnected \n");
}
catch(Exception e){
System.out.println(username+" failed to disconnect \n");
}
}
//send message to the server
public void sendMessage() throws IOException{
try{
inReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outWriter = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
}
catch(IOException ioe){
}
//infinite loop to check for messages
try{
String response;
String inputMsg = inReader.readLine();
outWriter.println(inputMsg);
while((response = inReader.readLine()) != null){
System.out.println(response);
outWriter.println(inputMsg);
}
inReader.close();
outWriter.close();
//clientGUI.appendMessage(inputMsg);
}
catch(IOException ioe){
}
}
void appendToCG(String str){
clientGUI.appendMessage(str);
}
public static void main(String[] args) {
Client client = new Client("127.0.0.1",port);
}
}
修改
我的startServerConnection()
课程中的 Server
方法:
public void startServerConnection()
{
try {
serverSocket = new ServerSocket(portNumber);
while(connection){
System.out.println("Waiting for a client...");
Socket clientSocket = serverSocket.accept();
System.out.println("Server connection established on port: "+clientSocket.getLocalPort());
ClientConnectionHandler clientConnection = new ClientConnectionHandler(clientSocket);
Thread thread = new Thread(clientConnection);
thread.start();
}
}
catch (Exception e) {
// System.out.println(sdf.format(new
// Date())+": Server didn't connect"); //append to eventsLog
e.printStackTrace();
return;
}
}
我非常确定我已经在ClientConnectionHandler
(每个用户发送消息)和Client
阅读消息时创建了所有必需的读者和作者。我错过了什么吗?
答案 0 :(得分:1)
可能不是全分辨率,但是:
ClientConnectionHandler扩展了Thread。它应该可以扩展Runnable,因为你在startServerConnection()中创建了一个Thread。
您似乎正在尝试在 @model Pulse.Models.Templates
@{
ViewBag.Title = "Index";
}
<div class="container">
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<h2>Select your Template</h2>
@Html.DropDownList("TemplatesCategory")
<script type="text/javascript">
$(document).ready(function () {
$("#TemplatesCategory").change(function () {
var choice = this.value;
if (choice === "1") {
$.ajax({
url: '/template/Footwear',
contentType: 'application/html;charset=utf-8',
type: 'GET',
datatype:'html'
})
.success(function(result){
$('#templateContainer').html(result)
})
}
else if (choice === "2") {
$.ajax({
url: '/template/Accessory',
contentType: 'application/html;charset=utf-8',
type: 'GET',
datatype: 'html'
})
.success(function (result) {
$('#templateContainer').html(result)
})
}
else if (choice === "3") {
$.ajax({
url: '/template/Clothing',
contentType: 'application/html;charset=utf-8',
type: 'GET',
datatype: 'html'
})
.success(function (result) {
$('#templateContainer').html(result)
})
}
});
});
</script>
<div id="templateContainer"></div>
</div>
和namespace Pulse.Models
{
using System;
using System.Collections.Generic;
public partial class Templates
{
public Templates()
{
this.templateAccessoriesTbls = new HashSet<templateAccessories>();
this.templateClothingTbls = new HashSet<templateClothing>();
this.templateFootwearTbls = new HashSet<templateFootwear>();
}
public int Id { get; set; }
public string templateName { get; set; }
public virtual ICollection<templateAccessories> templateAccessoriesTbls { get; set; }
public virtual ICollection<templateClothing> templateClothingTbls { get; set; }
public virtual ICollection<templateFootwear> templateFootwearTbls { get; set; }
}
}
之间重用ClientConnectionHandler。这种方法可能不是你想要的。您可能希望为客户端提供不同的Server
。我没有考虑过所有影响,但您可以制作Client
类工具Runnable
,然后更改Client
Runnable
在Client
方法中:
一个。你想发什么信息?你必须从某个地方收集意见
湾请勿在方法中附加和关闭流。
因此,大概在public void connectClient(){
try{
clientSocket = new Socket("127.0.0.1", port);
// set a timeout here, or you will block the IO! Alternatively,
// use the NIO stuff
Thread thread = new Thread(this);
thread.start();
String connected = sdf.format(new Date())+"\n"+username+" just connected \n";
System.out.println(connected);
}
catch(Exception e){
System.out.println(sdf.format(new Date())+"\n"+username+" did not connect to server "+e+"\n");
}
}
public void run() {
try {
clientSocket.setSoTimeout(1000);
//loop to read messages sent to *this* client
while (true) {
try {
String inputMsg = reader.readLine();
// just print to stdout; might want to update some GUI
System.out.println(inputMsg);
}
catch (SocketTimeoutException noop) { }
} //end of while loop
}
catch (Exception e) {
// note that this error may not be a problem since
// disconnect client will close the socket, which will
// cause an error at some future point.
System.err.println(e);
}
}
}
课程中,您需要执行以下操作:
Client.sendMessage()